Skip to content

Commit

Permalink
cty: AsBigFloat must make a deep copy
Browse files Browse the repository at this point in the history
Use Float.Copy in AsBigFloat to ensure that there is no shared data
between the mutable *big.Float and the cty.Value internal state.

big.Float includes some pointers, so a shallow copy is insufficient.
  • Loading branch information
jbardin committed Aug 17, 2021
1 parent aba65fb commit c8f22cd
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
4 changes: 1 addition & 3 deletions cty/value_ops.go
Expand Up @@ -1283,9 +1283,7 @@ func (val Value) AsBigFloat() *big.Float {
}

// Copy the float so that callers can't mutate our internal state
ret := *(val.v.(*big.Float))

return &ret
return new(big.Float).Copy(val.v.(*big.Float))
}

// AsValueSlice returns a []cty.Value representation of a non-null, non-unknown
Expand Down
13 changes: 13 additions & 0 deletions cty/value_ops_test.go
Expand Up @@ -3442,3 +3442,16 @@ func TestHasWhollyKnownType(t *testing.T) {
})
}
}

func TestFloatCopy(t *testing.T) {
// ensure manipulating floats does not modify the cty.Value
v := NumberFloatVal(1.9)
vString := v.GoString()

// do something that will modify the internal big.Float mantissa
v.AsBigFloat().SetInt64(1)

if vString != v.GoString() {
t.Fatalf("original value changed from %s to %#v", vString, v)
}
}

0 comments on commit c8f22cd

Please sign in to comment.