diff options
author | mattdee123 <mattdee123@gmail.com> | 2017-05-17 22:58:21 +0800 |
---|---|---|
committer | Victor Quinn <mail@victorquinn.com> | 2017-05-17 22:58:21 +0800 |
commit | d5fda14026cb2f519715d2714468043fa0ace48e (patch) | |
tree | f5e5599251751f86ea776c45f123199617af8efb | |
parent | 3868940cdd7294e8db0acf28108a9ace9ff7a36d (diff) | |
download | dexon-decimal-d5fda14026cb2f519715d2714468043fa0ace48e.tar.gz dexon-decimal-d5fda14026cb2f519715d2714468043fa0ace48e.tar.zst dexon-decimal-d5fda14026cb2f519715d2714468043fa0ace48e.zip |
Defensive Copy on Coefficient (#52)
-rw-r--r-- | decimal.go | 4 | ||||
-rw-r--r-- | decimal_test.go | 4 |
2 files changed, 7 insertions, 1 deletions
@@ -443,7 +443,9 @@ func (d Decimal) Exponent() int32 { // Coefficient returns the coefficient of the decimal. It is scaled by 10^Exponent() 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. diff --git a/decimal_test.go b/decimal_test.go index a0ad37c..96f7340 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -1421,6 +1421,10 @@ func TestDecimal_Coefficient(t *testing.T) { if co.Int64() != 123 { 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 |