Skip to content

Commit

Permalink
internal/number: possible out of range error avoiding
Browse files Browse the repository at this point in the history
Case when r.Increment > 0 and r.IncrementScale == len(scales) in *Decimal.ConvertFloat method is taken into account.
It led to unexpected out of range panic.

fixes golang/go#42147

Change-Id: Ic26e67010b766bdbd322a3853489f6d1ecb0dcfc
Reviewed-on: https://go-review.googlesource.com/c/text/+/265021
Reviewed-by: Marcel van Lohuizen <[email protected]>
Trust: Russ Cox <[email protected]>
  • Loading branch information
igor-v-bolotnikov authored and rsc committed Nov 25, 2020
1 parent 72ead5f commit 305da72
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/number/decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ func (d *Decimal) ConvertFloat(r RoundingContext, x float64, size int) {
if r.Increment > 0 {
scale := int(r.IncrementScale)
mult := 1.0
if scale > len(scales) {
if scale >= len(scales) {
mult = math.Pow(10, float64(scale))
} else {
mult = scales[scale]
Expand Down
5 changes: 5 additions & 0 deletions internal/number/decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,10 @@ func TestConvert(t *testing.T) {
inc0_05 := RoundingContext{Increment: 5, IncrementScale: 2}
inc0_05.SetScale(2)
inc50 := RoundingContext{Increment: 50}
incScaleEqualToScalesLen := RoundingContext{Increment: 1, IncrementScale: 0}
if len(scales) <= math.MaxUint8 {
incScaleEqualToScalesLen.IncrementScale = uint8(len(scales))
}
prec3 := RoundingContext{}
prec3.SetPrecision(3)
roundShift := RoundingContext{DigitShift: 2, MaxFractionDigits: 2}
Expand Down Expand Up @@ -309,6 +313,7 @@ func TestConvert(t *testing.T) {
{math.Inf(-1), inc50, "-Inf"},
{math.NaN(), inc50, "NaN"},
{"clearly not a number", scale2, "NaN"},
{0.0, incScaleEqualToScalesLen, "0"},
}
for _, tc := range testCases {
var d Decimal
Expand Down

0 comments on commit 305da72

Please sign in to comment.