diff options
| author | Shulhan <ms@kilabit.info> | 2021-11-17 10:41:27 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2021-11-17 10:41:27 +0700 |
| commit | ea0846a642f7a8bc0d07e776ff9ca64f9f27992d (patch) | |
| tree | 9f3aea8819359a812c1d89e7ac73754fb42e6371 | |
| parent | 339a047adea6c13d294460b9d77b9b48fadcb003 (diff) | |
| download | pakakeh.go-ea0846a642f7a8bc0d07e776ff9ca64f9f27992d.tar.xz | |
math/big: return nil on Quo and QuoRat instead of panic
Previously, if the first parameter of Quo or the second/next parameters
of QuoRat is not convertable to Rat or zero, the method/function will
panic.
This changes make it less intrunsive, instead of panic we check for
zero value and return nil immediately.
| -rw-r--r-- | lib/math/big/rat.go | 16 | ||||
| -rw-r--r-- | lib/math/big/rat_test.go | 5 |
2 files changed, 13 insertions, 8 deletions
diff --git a/lib/math/big/rat.go b/lib/math/big/rat.go index bd1e9863..c7158210 100644 --- a/lib/math/big/rat.go +++ b/lib/math/big/rat.go @@ -99,6 +99,8 @@ func MustRat(v interface{}) (r *Rat) { // // QuoRat return the quotient of `f/g/...` as new Rat. +// If the second or rest of parameters can not be converted to Rat or zero it +// will return nil instead of panic. // func QuoRat(f ...interface{}) *Rat { if len(f) == 0 { @@ -109,9 +111,9 @@ func QuoRat(f ...interface{}) *Rat { return nil } for x := 1; x < len(f); x++ { - rx := toRat(f[x], nil) - if rx == nil { - continue + rx := toRat(f[x]) + if rx == nil || rx.IsZero() { + return nil } total.Quo(rx) } @@ -319,15 +321,15 @@ func (r *Rat) Mul(g interface{}) *Rat { // // Quo sets r to quotient of `r/g` and return the result as r. -// If g is not convertible to Rat it will return nil. +// If g is not convertible to Rat or zero it will return nil. // func (r *Rat) Quo(g interface{}) *Rat { - y := toRat(g, nil) - if y == nil { + y := toRat(g) + if y == nil || y.IsZero() { return nil } r.Rat.Quo(&r.Rat, &y.Rat) - r.SetString(r.String()) + r.Rat.SetString(r.String()) return r } diff --git a/lib/math/big/rat_test.go b/lib/math/big/rat_test.go index f5314e92..271d14ab 100644 --- a/lib/math/big/rat_test.go +++ b/lib/math/big/rat_test.go @@ -79,7 +79,7 @@ func TestQuoRat(t *testing.T) { "a", NewRat("0.3"), }, - exp: "20", + exp: "", }, { ins: []interface{}{ 4651, @@ -98,6 +98,9 @@ func TestQuoRat(t *testing.T) { "25394000000", }, exp: "0.00100395", + }, { + ins: []interface{}{2, 0, 2}, + exp: "", }} for _, c := range cases { |
