aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authormattdee123 <mattdee123@gmail.com>2017-05-17 22:58:21 +0800
committerVictor Quinn <mail@victorquinn.com>2017-05-17 22:58:21 +0800
commitd5fda14026cb2f519715d2714468043fa0ace48e (patch)
treef5e5599251751f86ea776c45f123199617af8efb
parent3868940cdd7294e8db0acf28108a9ace9ff7a36d (diff)
downloaddexon-decimal-d5fda14026cb2f519715d2714468043fa0ace48e.tar.gz
dexon-decimal-d5fda14026cb2f519715d2714468043fa0ace48e.tar.zst
dexon-decimal-d5fda14026cb2f519715d2714468043fa0ace48e.zip
Defensive Copy on Coefficient (#52)
-rw-r--r--decimal.go4
-rw-r--r--decimal_test.go4
2 files changed, 7 insertions, 1 deletions
diff --git a/decimal.go b/decimal.go
index 5fcb628..cf0f3ce 100644
--- a/decimal.go
+++ b/decimal.go
@@ -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