Defensive Copy on Coefficient (#52)

This commit is contained in:
mattdee123 2017-05-17 10:58:21 -04:00 committed by Victor Quinn
parent 3868940cdd
commit d5fda14026
2 changed files with 7 additions and 1 deletions

View file

@ -443,7 +443,9 @@ func (d Decimal) Exponent() int32 {
// Coefficient returns the coefficient of the decimal. It is scaled by 10^Exponent() // Coefficient returns the coefficient of the decimal. It is scaled by 10^Exponent()
func (d Decimal) Coefficient() *big.Int { func (d Decimal) Coefficient() *big.Int {
return d.value // we copy the coefficient so that mutating the result does not mutate the
// Decimal.
return big.NewInt(0).Set(d.value)
} }
// IntPart returns the integer component of the decimal. // IntPart returns the integer component of the decimal.

View file

@ -1421,6 +1421,10 @@ func TestDecimal_Coefficient(t *testing.T) {
if co.Int64() != 123 { if co.Int64() != 123 {
t.Error("Coefficient should be 123; Got:", co) t.Error("Coefficient should be 123; Got:", co)
} }
co.Set(big.NewInt(0))
if d.IntPart() != 123 {
t.Error("Modifying coefficient modified Decimal; Got:", d)
}
} }
type DecimalSlice []Decimal type DecimalSlice []Decimal