Skip to content

Commit

Permalink
cty: AsBigFloat does a shallow 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.
  • Loading branch information
jbardin committed Aug 4, 2021
1 parent 8fee7bd commit 6930289
Show file tree
Hide file tree
Showing 2 changed files with 16 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
15 changes: 15 additions & 0 deletions cty/value_ops_test.go
Expand Up @@ -3432,3 +3432,18 @@ 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
f := v.AsBigFloat()
i, _ := f.Int(nil)
f.SetInt(i)

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

0 comments on commit 6930289

Please sign in to comment.