This is an automated email from the ASF dual-hosted git repository.
zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-go.git
The following commit(s) were added to refs/heads/main by this push:
new 992b6c01 fix(arrow/decimal): round exact halfway strings consistently
in FromString (#1519)
992b6c01 is described below
commit 992b6c01e82e2099dbea64a1895bab12bd00a1e8
Author: ump45nose <[email protected]>
AuthorDate: Tue Nov 17 00:25:35 2026 +0800
fix(arrow/decimal): round exact halfway strings consistently in FromString
(#1519)
### Rationale for this change
`FromString` scaled a binary approximation of the input and then added
one half before truncating. Exact decimal ties such as `0.35` and `0.15`
are not representable in binary, so they landed just below or just above
one half and rounded in different directions (`0.35` at scale 1 gave 3,
`0.15` gave 2). Negative scales also truncated (`"15"` and `"19"` at
scale -1 both gave 1).
### What changes are included in this PR?
A small internal helper, `arrow/internal/decimalstr`, rounds a plain
decimal literal multiplied by `10^scale` directly from its digits, with
ties away from zero. `decimal.Decimal32FromString`,
`decimal.Decimal64FromString`, `decimal128.FromString` and
`decimal256.FromString` parse those literals first and skip
`big.ParseFloat` on that path. Magnitude checks use the number of
integer digits after scaling, and still reject an oversized unscaled
value before a negative scale is applied. The coefficient is built from
the integer and fractional parts separately and scaled with a
powers-of-ten table.
Inputs that are not plain decimal literals (for example a binary `p`
exponent, which `big.ParseFloat` accepts) keep the previous float
rounding. Overflows that used to make `big.ParseFloat` return ±Inf, such
as `1e1000000000`, now fail with the same `bitlen too large` error as
other huge finite literals.
Only the digits that are kept are bounded. Any number of dropped
fraction digits is accepted, and because ties round away from zero, only
the first dropped digit decides the rounding.
### Are these changes tested?
Yes. `TestFromStringRoundsExactTies` in `arrow/decimal`,
`arrow/decimal128` and `arrow/decimal256` covers the original ties and
negative-scale cases (`15`/`19` at scale -1). The helper has unit tests
for rounding, rejected inputs, digit bounds, tiny exponents and the
float fallback. `go test` for `./arrow/decimal{,128,256}`,
`./arrow/internal/decimalstr`, `./arrow/array`, `./arrow/scalar`,
`./parquet/schema` and `./parquet/variant` is green with Go 1.27. A
local benchmark of `decimal128.FromString` on an Intel Xeon is faster
than current main on the same inputs (`12345.6789` at scale 4: 488 ns /
11 allocs on main, 285 ns / 6 allocs here).
### Are there any user-facing changes?
Yes. In-range values that are exact decimal ties now consistently round
half away from zero, for example `0.35` at scale 1 now gives 4 instead
of 3. Negative scales use the same rule, so `FromString("15", 38, -1)`
and `FromString("19", 38, -1)` now return 2 rather than 1. No public API
change.
Closes #1518.
---
This change was prepared with AI assistance and reviewed before
submission.
---
arrow/decimal/decimal.go | 78 ++---
arrow/decimal/decimal_test.go | 66 ++++-
arrow/decimal128/decimal128.go | 87 +++---
arrow/decimal128/decimal128_test.go | 73 ++++-
arrow/decimal256/decimal256.go | 82 +++---
arrow/decimal256/decimal256_test.go | 72 ++++-
arrow/internal/decimalstr/decimalstr.go | 409 +++++++++++++++++++++++++++
arrow/internal/decimalstr/decimalstr_test.go | 156 ++++++++++
8 files changed, 916 insertions(+), 107 deletions(-)
diff --git a/arrow/decimal/decimal.go b/arrow/decimal/decimal.go
index 75ac8ef9..4624b562 100644
--- a/arrow/decimal/decimal.go
+++ b/arrow/decimal/decimal.go
@@ -28,6 +28,7 @@ import (
"github.com/apache/arrow-go/v18/arrow/decimal128"
"github.com/apache/arrow-go/v18/arrow/decimal256"
"github.com/apache/arrow-go/v18/arrow/internal/debug"
+ "github.com/apache/arrow-go/v18/arrow/internal/decimalstr"
)
// DecimalTypes is a generic constraint representing the implemented decimal
types
@@ -180,14 +181,46 @@ func (n Decimal64) ToString(scale int32) string {
return n.ToBigFloat(scale).Text('f', int(scale))
}
-var pt5 = big.NewFloat(0.5)
-
func decimalFromString[T interface {
Decimal32 | Decimal64
FitsInPrecision(int32) bool
}](v string, prec, scale int32) (n T, err error) {
var nbits = uint(unsafe.Sizeof(T(0))) * 8
+ if lit, ok := decimalstr.Parse(v); ok {
+ return fromDecimalLiteral[T](lit, prec, scale, nbits)
+ }
+ return fromFloatLiteral[T](v, prec, scale, nbits)
+}
+
+func fromDecimalLiteral[T interface {
+ Decimal32 | Decimal64
+ FitsInPrecision(int32) bool
+}](lit decimalstr.Parsed, prec, scale int32, nbits uint) (n T, err error) {
+ if scale < 0 {
+ // Check the unscaled magnitude before using the scale,
matching the
+ // previous MantExp > nbits bound (|x| >= 2^nbits).
+ if lit.AtLeastTwoPower(0, int(nbits)) {
+ return n, fmt.Errorf("bitlen too large for decimal%d",
nbits)
+ }
+ } else if lit.AtLeastTwoPower(int64(scale), int(nbits)) {
+ return n, fmt.Errorf("bitlen too large for decimal%d", nbits)
+ }
+
+ val, ok := lit.ScaleAndRound(int64(scale))
+ if !ok || val.BitLen() >= int(nbits) {
+ return n, fmt.Errorf("bitlen too large for decimal%d", nbits)
+ }
+ n = T(val.Int64())
+ if !n.FitsInPrecision(prec) {
+ err = fmt.Errorf("val %v doesn't fit in precision %d", n, prec)
+ }
+ return
+}
+func fromFloatLiteral[T interface {
+ Decimal32 | Decimal64
+ FitsInPrecision(int32) bool
+}](v string, prec, scale int32, nbits uint) (n T, err error) {
var out *big.Float
out, _, err = big.ParseFloat(v, 10, nbits, big.ToNearestEven)
if err != nil {
@@ -203,46 +236,25 @@ func decimalFromString[T interface {
if out.MantExp(nil) > int(nbits) {
return n, fmt.Errorf("bitlen too large for decimal%d",
nbits)
}
- var tmp big.Int
- val, _ := out.Int(&tmp)
+ }
- // |val| < 2^64 < 10^20, so a larger divisor gives the same
quotient.
- div := new(big.Int).Exp(big.NewInt(10),
big.NewInt(min(-int64(scale), 20)), nil)
- n = T(val.Quo(val, div).Int64())
- } else {
- // Clamp before converting, since converting an out of range
float to
- // uint is implementation specific. SetPrec caps at big.MaxPrec
anyway.
+ if scale != 0 {
bitsNeeded := math.Round(float64(int64(prec)+int64(scale)+1) /
math.Log10(2))
var precInBits = uint(min(max(bitsNeeded, 0), big.MaxPrec-1)) +
1
-
mulPow10(out.SetPrec(precInBits), int64(scale))
// Reject before rounding and converting, which would allocate
as many
// bits as the value has.
- if out.IsInf() || out.MantExp(nil) > int(nbits) {
+ if scale > 0 && (out.IsInf() || out.MantExp(nil) > int(nbits)) {
return n, fmt.Errorf("bitlen too large for decimal%d",
nbits)
}
- // A magnitude below 1/4 rounds to zero. Clearing it skips the
- // rounding below, which allocates in proportion to the gap
between
- // the value's exponent and 0.5's.
- if out.MantExp(nil) < -1 {
- out.SetInt64(0)
- }
- if out.Signbit() {
- out.Sub(out, pt5)
- } else {
- out.Add(out, pt5)
- }
-
- var tmp big.Int
- val, _ := out.Int(&tmp)
- // This also rejects the signed minimum, which fits the storage
but has
- // more digits than the maximum precision allows.
- if val.BitLen() >= int(nbits) {
- return n, fmt.Errorf("bitlen too large for decimal%d",
nbits)
- }
- n = T(val.Int64())
}
-
+ val := decimalstr.RoundScaled(out, v, int64(scale))
+ // This also rejects the signed minimum, which fits the storage but has
+ // more digits than the maximum precision allows.
+ if val.BitLen() >= int(nbits) {
+ return n, fmt.Errorf("bitlen too large for decimal%d", nbits)
+ }
+ n = T(val.Int64())
if !n.FitsInPrecision(prec) {
err = fmt.Errorf("val %v doesn't fit in precision %d", n, prec)
}
diff --git a/arrow/decimal/decimal_test.go b/arrow/decimal/decimal_test.go
index 663105eb..49cff5f7 100644
--- a/arrow/decimal/decimal_test.go
+++ b/arrow/decimal/decimal_test.go
@@ -22,6 +22,7 @@ import (
"math/big"
"runtime"
"strconv"
+ "strings"
"testing"
"github.com/apache/arrow-go/v18/arrow/decimal"
@@ -340,7 +341,7 @@ func TestFromString(t *testing.T) {
}
n32, err := decimal.Decimal32FromString("4294967295", 9, -1)
require.NoError(t, err)
- assert.Equal(t, decimal.Decimal32(429496729), n32)
+ assert.Equal(t, decimal.Decimal32(429496730), n32)
_, err = decimal.Decimal32FromString("4294967296", 9, -1)
assert.ErrorContains(t, err, "bitlen too large for decimal32")
_, err = decimal.Decimal64FromString("9223372036854775808", 18, 0)
@@ -353,7 +354,7 @@ func TestFromString(t *testing.T) {
scale int32
want decimal.Decimal64
}{
- {"9223372036854775808", -1, 922337203685477580},
+ {"9223372036854775808", -1, 922337203685477581},
{"18446744073709551615", -2, 184467440737095516},
{"10000000000000000000", -19, 1},
{"18000000000000000000", -20, 0},
@@ -626,3 +627,64 @@ func TestDecimalBasics(t *testing.T) {
assert.EqualValues(t, expmod, mod64)
}
}
+
+func TestFromStringRoundsExactTies(t *testing.T) {
+ // These halfway values are not exact in binary, so rounding a binary
+ // approximation sent some of them down. Ties round away from zero.
+ tests := []struct {
+ s string
+ scale int32
+ expected int64
+ }{
+ {"0.35", 1, 4},
+ {"0.15", 1, 2},
+ {"2.675", 2, 268},
+ {"1.005", 2, 101},
+ {"-0.35", 1, -4},
+ {"-1.005", 2, -101},
+ {"19", -1, 2},
+ {"15", -1, 2},
+ {"14", -1, 1},
+ {"-15", -1, -2},
+ {"-19", -1, -2},
+ }
+ for _, tt := range tests {
+ t.Run(fmt.Sprintf("%s_%d", tt.s, tt.scale), func(t *testing.T) {
+ n32, err := decimal.Decimal32FromString(tt.s, 9,
tt.scale)
+ require.NoError(t, err)
+ assert.EqualValues(t, tt.expected, n32)
+
+ n64, err := decimal.Decimal64FromString(tt.s, 18,
tt.scale)
+ require.NoError(t, err)
+ assert.EqualValues(t, tt.expected, n64)
+ })
+ }
+}
+
+func TestFromStringLongFraction(t *testing.T) {
+ // Fractions longer than 1024 digits must still round from the first
+ // dropped digit instead of being rejected as too large.
+ tests := []struct {
+ s string
+ scale int32
+ expected int64
+ }{
+ {"0." + strings.Repeat("7", 1000), 2, 78},
+ {"0." + strings.Repeat("7", 1030), 2, 78},
+ {"0." + strings.Repeat("7", 5000), 2, 78},
+ {"-0." + strings.Repeat("7", 5000), 2, -78},
+ {"0.125" + strings.Repeat("0", 2000), 2, 13},
+ {"0.124" + strings.Repeat("9", 2000), 2, 12},
+ }
+ for i, tt := range tests {
+ t.Run(fmt.Sprintf("%d_%d", i, len(tt.s)), func(t *testing.T) {
+ n32, err := decimal.Decimal32FromString(tt.s, 9,
tt.scale)
+ require.NoError(t, err)
+ assert.EqualValues(t, tt.expected, n32)
+
+ n64, err := decimal.Decimal64FromString(tt.s, 18,
tt.scale)
+ require.NoError(t, err)
+ assert.EqualValues(t, tt.expected, n64)
+ })
+ }
+}
diff --git a/arrow/decimal128/decimal128.go b/arrow/decimal128/decimal128.go
index 940a841e..faf99908 100644
--- a/arrow/decimal128/decimal128.go
+++ b/arrow/decimal128/decimal128.go
@@ -25,6 +25,7 @@ import (
"strings"
"github.com/apache/arrow-go/v18/arrow/internal/debug"
+ "github.com/apache/arrow-go/v18/arrow/internal/decimalstr"
)
const (
@@ -238,9 +239,41 @@ func FromFloat64(v float64, prec, scale int32) (Num,
error) {
return fromPositiveFloat64(v, prec, scale)
}
-var pt5 = big.NewFloat(0.5)
-
func FromString(v string, prec, scale int32) (n Num, err error) {
+ if lit, ok := decimalstr.Parse(v); ok {
+ return fromDecimalLiteral(lit, prec, scale)
+ }
+ return fromFloatLiteral(v, prec, scale)
+}
+
+func fromDecimalLiteral(lit decimalstr.Parsed, prec, scale int32) (n Num, err
error) {
+ if scale < 0 {
+ // Reject an unscaled magnitude that would not fit in signed
128-bit
+ // storage, before using the scale.
+ if lit.AtLeastTwoPower(0, 127) {
+ return Num{}, errors.New("bitlen too large for
decimal128")
+ }
+ if scale < -MaxScale {
+ return Num{}, fmt.Errorf("scale %d out of range for
decimal128, must be between %d and %d", scale, -MaxScale, MaxScale)
+ }
+ } else if scale > MaxScale {
+ return Num{}, fmt.Errorf("scale %d out of range for decimal128,
must be between %d and %d", scale, -MaxScale, MaxScale)
+ } else if lit.AtLeastTwoPower(int64(scale), 128) {
+ return Num{}, errors.New("bitlen too large for decimal128")
+ }
+
+ val, ok := lit.ScaleAndRound(int64(scale))
+ if !ok || val.BitLen() > 127 {
+ return Num{}, errors.New("bitlen too large for decimal128")
+ }
+ n = FromBigInt(val)
+ if !n.FitsInPrecision(prec) {
+ err = fmt.Errorf("val %v doesn't fit in precision %d", n, prec)
+ }
+ return
+}
+
+func fromFloatLiteral(v string, prec, scale int32) (n Num, err error) {
// time for some math!
// Our input precision means "number of digits of precision" but the
// math/big library refers to precision in floating point terms
@@ -287,45 +320,29 @@ func FromString(v string, prec, scale int32) (n Num, err
error) {
if scale < -MaxScale {
return Num{}, fmt.Errorf("scale %d out of range for
decimal128, must be between %d and %d", scale, -MaxScale, MaxScale)
}
- var tmp big.Int
- val, _ := out.Int(&tmp)
- n = FromBigInt(val)
- n, _ = n.Div(scaleMultipliers[-scale])
- } else {
- if scale > MaxScale {
- return Num{}, fmt.Errorf("scale %d out of range for
decimal128, must be between %d and %d", scale, -MaxScale, MaxScale)
+ } else if scale > MaxScale {
+ return Num{}, fmt.Errorf("scale %d out of range for decimal128,
must be between %d and %d", scale, -MaxScale, MaxScale)
+ }
+
+ if scale != 0 {
+ if scale > 0 {
+ p :=
(&big.Float{}).SetInt(scaleMultipliers[scale].BigInt())
+ out.SetPrec(precInBits).Mul(out, p)
+ } else {
+ p :=
(&big.Float{}).SetInt(scaleMultipliers[-scale].BigInt())
+ out.SetPrec(precInBits).Quo(out, p)
}
- // Since we're going to truncate this to get an integer, we
need to round
- // the value instead because of edge cases so that we match how
other implementations
- // (e.g. C++) handles Decimal values. So if we're negative
we'll subtract 0.5 and if
- // we're positive we'll add 0.5.
- p := (&big.Float{}).SetInt(scaleMultipliers[scale].BigInt())
- out.SetPrec(precInBits).Mul(out, p)
// Reject before rounding and converting, which would allocate
as many
// bits as the value has.
- if out.IsInf() || out.MantExp(nil) > 128 {
+ if scale > 0 && (out.IsInf() || out.MantExp(nil) > 128) {
return Num{}, errors.New("bitlen too large for
decimal128")
}
- // A magnitude below 1/4 rounds to zero. Clearing it skips the
- // rounding below, which allocates in proportion to the gap
between
- // the value's exponent and 0.5's.
- if out.MantExp(nil) < -1 {
- out.SetInt64(0)
- }
- if out.Signbit() {
- out.Sub(out, pt5)
- } else {
- out.Add(out, pt5)
- }
-
- var tmp big.Int
- val, _ := out.Int(&tmp)
- if val.BitLen() > 127 {
- return Num{}, errors.New("bitlen too large for
decimal128")
- }
- n = FromBigInt(val)
}
-
+ val := decimalstr.RoundScaled(out, v, int64(scale))
+ if val.BitLen() > 127 {
+ return Num{}, errors.New("bitlen too large for decimal128")
+ }
+ n = FromBigInt(val)
if !n.FitsInPrecision(prec) {
err = fmt.Errorf("val %v doesn't fit in precision %d", n, prec)
}
diff --git a/arrow/decimal128/decimal128_test.go
b/arrow/decimal128/decimal128_test.go
index 6a829095..48df3f0a 100644
--- a/arrow/decimal128/decimal128_test.go
+++ b/arrow/decimal128/decimal128_test.go
@@ -21,6 +21,7 @@ import (
"math"
"math/big"
"runtime"
+ "strings"
"testing"
"github.com/apache/arrow-go/v18/arrow/decimal128"
@@ -724,13 +725,22 @@ func TestFromString(t *testing.T) {
})
}
- for _, s := range []string{"Inf", "+Inf", "-inf", "1e1000000000",
"-1e1000000000"} {
+ for _, s := range []string{"Inf", "+Inf", "-inf"} {
for _, scale := range []int32{2, -2} {
_, err := decimal128.FromString(s, 37, scale)
assert.ErrorContains(t, err, "cannot convert", "%s at
scale %d", s, scale)
}
}
+ // These used to overflow big.ParseFloat to ±Inf ("cannot convert"). The
+ // digit path reports the same overflow as other huge finite literals.
+ for _, s := range []string{"1e1000000000", "-1e1000000000"} {
+ for _, scale := range []int32{2, -2} {
+ _, err := decimal128.FromString(s, 37, scale)
+ assert.ErrorContains(t, err, "bitlen too large for
decimal128", "%s at scale %d", s, scale)
+ }
+ }
+
for _, tc := range []struct {
s string
scale int32
@@ -783,7 +793,10 @@ func TestBitLen(t *testing.T) {
limit.Sub(limit, big.NewInt(1))
got, err := decimal128.FromString(limit.String(),
decimal128.MaxPrecision, -1)
require.NoError(t, err)
- assert.Equal(t, limit.Quo(limit, big.NewInt(10)).String(),
got.BigInt().String())
+ // (2^127-1)/10 has remainder 7 and rounds away from zero.
+ want := new(big.Int).Quo(new(big.Int).Set(limit), big.NewInt(10))
+ want.Add(want, big.NewInt(1))
+ assert.Equal(t, want.String(), got.BigInt().String())
}
func TestFromStringDecimal128b(t *testing.T) {
@@ -855,3 +868,59 @@ func TestFromStringScaleOutOfRange(t *testing.T) {
_, err = decimal128.FromString("Inf", 38, 39)
assert.EqualError(t, err, "cannot convert Inf to decimal128")
}
+
+func TestFromStringRoundsExactTies(t *testing.T) {
+ // These halfway values are not exact in binary, so rounding a binary
+ // approximation sent some of them down. Ties round away from zero.
+ tests := []struct {
+ s string
+ scale int32
+ expected int64
+ }{
+ {"0.35", 1, 4},
+ {"0.15", 1, 2},
+ {"2.675", 1, 27},
+ {"2.675", 2, 268},
+ {"1.005", 2, 101},
+ {"-0.35", 1, -4},
+ {"-1.005", 2, -101},
+ {"0.349999", 1, 3},
+ {"35e-2", 1, 4},
+ {"19", -1, 2},
+ {"15", -1, 2},
+ {"14", -1, 1},
+ {"-15", -1, -2},
+ {"-19", -1, -2},
+ }
+ for _, tt := range tests {
+ t.Run(fmt.Sprintf("%s_%d", tt.s, tt.scale), func(t *testing.T) {
+ n, err := decimal128.FromString(tt.s, 38, tt.scale)
+ require.NoError(t, err)
+ assert.Equal(t, tt.expected, n.BigInt().Int64())
+ })
+ }
+}
+
+func TestFromStringLongFraction(t *testing.T) {
+ // Fractions longer than 1024 digits must still round from the first
+ // dropped digit instead of being rejected as too large.
+ tests := []struct {
+ s string
+ scale int32
+ expected int64
+ }{
+ {"0." + strings.Repeat("7", 1000), 2, 78},
+ {"0." + strings.Repeat("7", 1030), 2, 78},
+ {"0." + strings.Repeat("7", 5000), 2, 78},
+ {"-0." + strings.Repeat("7", 5000), 2, -78},
+ {"0.125" + strings.Repeat("0", 2000), 2, 13},
+ {"0.124" + strings.Repeat("9", 2000), 2, 12},
+ }
+ for i, tt := range tests {
+ t.Run(fmt.Sprintf("%d_%d", i, len(tt.s)), func(t *testing.T) {
+ n, err := decimal128.FromString(tt.s, 38, tt.scale)
+ require.NoError(t, err)
+ assert.Equal(t, tt.expected, n.BigInt().Int64())
+ })
+ }
+}
diff --git a/arrow/decimal256/decimal256.go b/arrow/decimal256/decimal256.go
index 314c9c0d..0cd80c39 100644
--- a/arrow/decimal256/decimal256.go
+++ b/arrow/decimal256/decimal256.go
@@ -26,6 +26,7 @@ import (
"github.com/apache/arrow-go/v18/arrow/decimal128"
"github.com/apache/arrow-go/v18/arrow/internal/debug"
+ "github.com/apache/arrow-go/v18/arrow/internal/decimalstr"
)
const (
@@ -118,9 +119,41 @@ func (n Num) Pow(rhs Num) Num {
return FromBigInt(b.Exp(b, rhs.BigInt(), nil))
}
-var pt5 = big.NewFloat(0.5)
-
func FromString(v string, prec, scale int32) (n Num, err error) {
+ if lit, ok := decimalstr.Parse(v); ok {
+ return fromDecimalLiteral(lit, prec, scale)
+ }
+ return fromFloatLiteral(v, prec, scale)
+}
+
+func fromDecimalLiteral(lit decimalstr.Parsed, prec, scale int32) (n Num, err
error) {
+ if scale < 0 {
+ // Reject an unscaled magnitude that would not fit in signed
256-bit
+ // storage, before using the scale.
+ if lit.AtLeastTwoPower(0, 255) {
+ return Num{}, errors.New("bitlen too large for
decimal256")
+ }
+ if scale < -MaxScale {
+ return Num{}, fmt.Errorf("scale %d out of range for
decimal256, must be between %d and %d", scale, -MaxScale, MaxScale)
+ }
+ } else if scale > MaxScale {
+ return Num{}, fmt.Errorf("scale %d out of range for decimal256,
must be between %d and %d", scale, -MaxScale, MaxScale)
+ } else if lit.AtLeastTwoPower(int64(scale), 256) {
+ return Num{}, errors.New("bitlen too large for decimal256")
+ }
+
+ val, ok := lit.ScaleAndRound(int64(scale))
+ if !ok || val.BitLen() > 255 {
+ return Num{}, errors.New("bitlen too large for decimal256")
+ }
+ n = FromBigInt(val)
+ if !n.FitsInPrecision(prec) {
+ err = fmt.Errorf("value %v doesn't fit in precision %d", n,
prec)
+ }
+ return
+}
+
+func fromFloatLiteral(v string, prec, scale int32) (n Num, err error) {
// time for some math!
// Our input precision means "number of digits of precision" but the
// math/big library refers to precision in floating point terms
@@ -167,44 +200,27 @@ func FromString(v string, prec, scale int32) (n Num, err
error) {
if scale < -MaxScale {
return Num{}, fmt.Errorf("scale %d out of range for
decimal256, must be between %d and %d", scale, -MaxScale, MaxScale)
}
- var tmp big.Int
- val, _ := out.Int(&tmp)
- n = FromBigInt(val)
+ } else if scale > MaxScale {
+ return Num{}, fmt.Errorf("scale %d out of range for decimal256,
must be between %d and %d", scale, -MaxScale, MaxScale)
+ }
- n, _ = n.Div(scaleMultipliers[-scale])
- } else {
- if scale > MaxScale {
- return Num{}, fmt.Errorf("scale %d out of range for
decimal256, must be between %d and %d", scale, -MaxScale, MaxScale)
+ if scale != 0 {
+ if scale > 0 {
+ out.Mul(out,
(&big.Float{}).SetInt(scaleMultipliers[scale].BigInt())).SetPrec(precInBits)
+ } else {
+ out.Quo(out,
(&big.Float{}).SetInt(scaleMultipliers[-scale].BigInt())).SetPrec(precInBits)
}
- out.Mul(out,
(&big.Float{}).SetInt(scaleMultipliers[scale].BigInt())).SetPrec(precInBits)
// Reject before rounding and converting, which would allocate
as many
// bits as the value has.
- if out.IsInf() || out.MantExp(nil) > 256 {
+ if scale > 0 && (out.IsInf() || out.MantExp(nil) > 256) {
return Num{}, errors.New("bitlen too large for
decimal256")
}
- // A magnitude below 1/4 rounds to zero. Clearing it skips the
- // rounding below, which allocates in proportion to the gap
between
- // the value's exponent and 0.5's.
- if out.MantExp(nil) < -1 {
- out.SetInt64(0)
- }
- // Since we're going to truncate this to get an integer, we
need to round
- // the value instead because of edge cases so that we match how
other implementations
- // (e.g. C++) handles Decimal values. So if we're negative
we'll subtract 0.5 and if
- // we're positive we'll add 0.5.
- if out.Signbit() {
- out.Sub(out, pt5)
- } else {
- out.Add(out, pt5)
- }
-
- var tmp big.Int
- val, _ := out.Int(&tmp)
- if val.BitLen() > 255 {
- return Num{}, errors.New("bitlen too large for
decimal256")
- }
- n = FromBigInt(val)
}
+ val := decimalstr.RoundScaled(out, v, int64(scale))
+ if val.BitLen() > 255 {
+ return Num{}, errors.New("bitlen too large for decimal256")
+ }
+ n = FromBigInt(val)
if !n.FitsInPrecision(prec) {
err = fmt.Errorf("value %v doesn't fit in precision %d", n,
prec)
}
diff --git a/arrow/decimal256/decimal256_test.go
b/arrow/decimal256/decimal256_test.go
index 3cb763f5..8a2e5264 100644
--- a/arrow/decimal256/decimal256_test.go
+++ b/arrow/decimal256/decimal256_test.go
@@ -633,13 +633,22 @@ func TestFromString(t *testing.T) {
})
}
- for _, s := range []string{"Inf", "+Inf", "-inf", "1e1000000000",
"-1e1000000000"} {
+ for _, s := range []string{"Inf", "+Inf", "-inf"} {
for _, scale := range []int32{2, -2} {
_, err := decimal256.FromString(s, 35, scale)
assert.ErrorContains(t, err, "cannot convert", "%s at
scale %d", s, scale)
}
}
+ // These used to overflow big.ParseFloat to ±Inf ("cannot convert"). The
+ // digit path reports the same overflow as other huge finite literals.
+ for _, s := range []string{"1e1000000000", "-1e1000000000"} {
+ for _, scale := range []int32{2, -2} {
+ _, err := decimal256.FromString(s, 35, scale)
+ assert.ErrorContains(t, err, "bitlen too large for
decimal256", "%s at scale %d", s, scale)
+ }
+ }
+
for _, tc := range []struct {
s string
scale int32
@@ -772,5 +781,64 @@ func TestBitLen(t *testing.T) {
limit.Sub(limit, big.NewInt(1))
got, err := decimal256.FromString(limit.String(),
decimal256.MaxPrecision, -1)
require.NoError(t, err)
- assert.Equal(t, limit.Quo(limit, big.NewInt(10)).String(),
got.BigInt().String())
+ // (2^255-1)/10 has remainder 7 and rounds away from zero.
+ want := new(big.Int).Quo(new(big.Int).Set(limit), big.NewInt(10))
+ want.Add(want, big.NewInt(1))
+ assert.Equal(t, want.String(), got.BigInt().String())
+}
+
+func TestFromStringRoundsExactTies(t *testing.T) {
+ // These halfway values are not exact in binary, so rounding a binary
+ // approximation sent some of them down. Ties round away from zero.
+ tests := []struct {
+ s string
+ scale int32
+ expected int64
+ }{
+ {"0.35", 1, 4},
+ {"0.15", 1, 2},
+ {"2.675", 1, 27},
+ {"2.675", 2, 268},
+ {"1.005", 2, 101},
+ {"-0.35", 1, -4},
+ {"-1.005", 2, -101},
+ {"0.349999", 1, 3},
+ {"35e-2", 1, 4},
+ {"19", -1, 2},
+ {"15", -1, 2},
+ {"14", -1, 1},
+ {"-15", -1, -2},
+ {"-19", -1, -2},
+ }
+ for _, tt := range tests {
+ t.Run(fmt.Sprintf("%s_%d", tt.s, tt.scale), func(t *testing.T) {
+ n, err := decimal256.FromString(tt.s, 76, tt.scale)
+ require.NoError(t, err)
+ assert.Equal(t, tt.expected, n.BigInt().Int64())
+ })
+ }
+}
+
+func TestFromStringLongFraction(t *testing.T) {
+ // Fractions longer than 1024 digits must still round from the first
+ // dropped digit instead of being rejected as too large.
+ tests := []struct {
+ s string
+ scale int32
+ expected int64
+ }{
+ {"0." + strings.Repeat("7", 1000), 2, 78},
+ {"0." + strings.Repeat("7", 1030), 2, 78},
+ {"0." + strings.Repeat("7", 5000), 2, 78},
+ {"-0." + strings.Repeat("7", 5000), 2, -78},
+ {"0.125" + strings.Repeat("0", 2000), 2, 13},
+ {"0.124" + strings.Repeat("9", 2000), 2, 12},
+ }
+ for i, tt := range tests {
+ t.Run(fmt.Sprintf("%d_%d", i, len(tt.s)), func(t *testing.T) {
+ n, err := decimal256.FromString(tt.s, 76, tt.scale)
+ require.NoError(t, err)
+ assert.Equal(t, tt.expected, n.BigInt().Int64())
+ })
+ }
}
diff --git a/arrow/internal/decimalstr/decimalstr.go
b/arrow/internal/decimalstr/decimalstr.go
new file mode 100644
index 00000000..97d8e1dd
--- /dev/null
+++ b/arrow/internal/decimalstr/decimalstr.go
@@ -0,0 +1,409 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package decimalstr holds helpers shared by the decimal packages for
+// working with decimal string literals.
+package decimalstr
+
+import (
+ "math"
+ "math/big"
+ "strconv"
+)
+
+// maxDigits bounds the number of integer digits ScaleAndRound will
+// materialize. It is well above the 77 digits a 256-bit value can hold, so it
+// only guards callers that skipped their own magnitude check.
+const maxDigits = 1024
+
+// maxPow10 is the largest exponent kept in pow10Table. It covers Decimal256
+// scales and the borderline magnitude checks; larger powers are computed on
+// demand only after the digit bound has already accepted the result size.
+const maxPow10 = 128
+
+var (
+ bigOne = big.NewInt(1)
+ pow10Table [maxPow10 + 1]*big.Int
+ twoPow32 = new(big.Int).Lsh(big.NewInt(1), 32)
+ twoPow64 = new(big.Int).Lsh(big.NewInt(1), 64)
+ twoPow127 = new(big.Int).Lsh(big.NewInt(1), 127)
+ twoPow128 = new(big.Int).Lsh(big.NewInt(1), 128)
+ twoPow255 = new(big.Int).Lsh(big.NewInt(1), 255)
+ twoPow256 = new(big.Int).Lsh(big.NewInt(1), 256)
+)
+
+func init() {
+ pow10Table[0] = big.NewInt(1)
+ ten := big.NewInt(10)
+ for i := 1; i <= maxPow10; i++ {
+ pow10Table[i] = new(big.Int).Mul(pow10Table[i-1], ten)
+ }
+}
+
+func pow10(n int) *big.Int {
+ if n <= maxPow10 {
+ return pow10Table[n]
+ }
+ return new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(n)), nil)
+}
+
+func twoPower(bits int) *big.Int {
+ switch bits {
+ case 32:
+ return twoPow32
+ case 64:
+ return twoPow64
+ case 127:
+ return twoPow127
+ case 128:
+ return twoPow128
+ case 255:
+ return twoPow255
+ case 256:
+ return twoPow256
+ default:
+ return new(big.Int).Lsh(big.NewInt(1), uint(bits))
+ }
+}
+
+// Parsed is a plain decimal literal: an optional sign, digits with an
+// optional fraction, and an optional decimal exponent. intPart and fracPart
+// are slices of the original string.
+type Parsed struct {
+ neg bool
+ intPart, fracPart string
+ exp int64
+}
+
+// Parse reports whether s is a plain decimal literal and, if so, returns
+// its parts. Inputs such as a p exponent, a hex prefix, Inf or NaN are
+// rejected so callers can fall back to their own conversion.
+func Parse(s string) (p Parsed, ok bool) {
+ if len(s) > 0 && (s[0] == '+' || s[0] == '-') {
+ p.neg = s[0] == '-'
+ s = s[1:]
+ }
+
+ intEnd := 0
+ for intEnd < len(s) && isDigit(s[intEnd]) {
+ intEnd++
+ }
+ p.intPart, s = s[:intEnd], s[intEnd:]
+
+ if len(s) > 0 && s[0] == '.' {
+ fracEnd := 1
+ for fracEnd < len(s) && isDigit(s[fracEnd]) {
+ fracEnd++
+ }
+ p.fracPart, s = s[1:fracEnd], s[fracEnd:]
+ }
+ if len(p.intPart)+len(p.fracPart) == 0 {
+ return Parsed{}, false
+ }
+
+ if len(s) > 0 {
+ if s[0] != 'e' && s[0] != 'E' {
+ return Parsed{}, false
+ }
+ digits := s[1:]
+ if len(digits) > 0 && (digits[0] == '+' || digits[0] == '-') {
+ digits = digits[1:]
+ }
+ if len(digits) == 0 {
+ return Parsed{}, false
+ }
+ for i := 0; i < len(digits); i++ {
+ if !isDigit(digits[i]) {
+ return Parsed{}, false
+ }
+ }
+ var err error
+ if p.exp, err = strconv.ParseInt(s[1:], 10, 64); err != nil {
+ return Parsed{}, false
+ }
+ }
+ return p, true
+}
+
+// ScaleAndRound returns the decimal literal s multiplied by 10^scale and
+// rounded to an integer, with ties rounded away from zero.
+//
+// It works on the decimal digits of s, so an exact halfway value such as
+// "0.15" or "0.35" is always recognized as a tie. Parsing into a binary
+// float first would leave it just above or just below one half, and the
+// rounding direction would depend on that error.
+//
+// ok is false when s is not a plain decimal literal or when the result
+// would have more than maxDigits digits; callers should then fall back to
+// their own conversion. Any number of dropped fraction digits is accepted.
+// Callers are expected to have bounded the magnitude of the result already.
+func ScaleAndRound(s string, scale int64) (val *big.Int, ok bool) {
+ p, ok := Parse(s)
+ if !ok {
+ return nil, false
+ }
+ return p.ScaleAndRound(scale)
+}
+
+// ScaleAndRound returns this literal multiplied by 10^scale and rounded
+// to an integer, with ties rounded away from zero.
+//
+// The coefficient is built from the integer and fractional parts separately
+// and scaled with a powers-of-ten table, so the hot path does not join
+// those parts into a new string or call big.Int.Exp.
+func (p Parsed) ScaleAndRound(scale int64) (val *big.Int, ok bool) {
+ fracLen := int64(len(p.fracPart))
+ const limit = int64(1) << 62
+ if p.exp > limit || p.exp < -limit || scale > limit || scale < -limit ||
+ fracLen > limit {
+ return nil, false
+ }
+ shift, ok := add2(p.exp, scale)
+ if !ok {
+ return nil, false
+ }
+ shift, ok = add2(shift, -fracLen)
+ if !ok {
+ return nil, false
+ }
+
+ digits := significantDigitCount(p.intPart, p.fracPart)
+ val = new(big.Int)
+ if digits == 0 {
+ return val, true
+ }
+
+ if shift >= 0 {
+ if int64(digits)+shift > maxDigits {
+ return nil, false
+ }
+ if !setCoeff(val, p.intPart, p.fracPart) {
+ return nil, false
+ }
+ if shift > 0 {
+ val.Mul(val, pow10(int(shift)))
+ }
+ } else {
+ down := -shift
+ // Every significant digit is to the right of the rounding
place,
+ // so the first dropped digit is an implied zero and the result
is 0.
+ if int64(digits) < down {
+ return val, true
+ }
+ if int64(digits)-down > maxDigits {
+ return nil, false
+ }
+ // Ties round away from zero, so only the first dropped digit
+ // matters. Cut the digit string instead of dividing, which
keeps
+ // the cost independent of how many fraction digits are dropped.
+ intLen := int64(len(p.intPart))
+ keep := intLen + int64(len(p.fracPart)) - down
+ var first byte
+ if keep < intLen {
+ if !setCoeff(val, p.intPart[:keep], "") {
+ return nil, false
+ }
+ first = p.intPart[keep]
+ } else {
+ if !setCoeff(val, p.intPart, p.fracPart[:keep-intLen]) {
+ return nil, false
+ }
+ first = p.fracPart[keep-intLen]
+ }
+ if first >= '5' {
+ val.Add(val, bigOne)
+ }
+ }
+
+ if p.neg {
+ val.Neg(val)
+ }
+ return val, true
+}
+
+// AtLeastTwoPower reports whether the absolute value of this literal
+// multiplied by 10^scale is at least 2^bits. The comparison uses the number
+// of integer digits after scaling and only materializes a coefficient on
+// the borderline, so a huge exponent does not allocate in proportion to
+// its size.
+func (p Parsed) AtLeastTwoPower(scale int64, bits int) bool {
+ if bits <= 0 {
+ return significantDigitCount(p.intPart, p.fracPart) > 0
+ }
+ e, ok := scaledExp(p, scale)
+ if !ok {
+ // Overflow of the combined exponent: a huge positive power is
at
+ // least 2^bits, a huge negative power is a fraction.
+ return p.exp > 0 || scale > 0
+ }
+ d := significantDigitCount(p.intPart, p.fracPart)
+ if d == 0 {
+ return false
+ }
+ // |x| is in [10^{d+e-1}, 10^{d+e}).
+ // 2^bits is in [10^{td-1}, 10^td), where td = floor(bits*log10(2))+1.
+ sum, ok := add2(int64(d), e)
+ if !ok {
+ return e > 0
+ }
+ td := int64(decimalDigitsOfTwoPower(bits))
+ if sum-1 >= td {
+ return true
+ }
+ if sum <= td-1 {
+ return false
+ }
+
+ // Borderline: compare coeff * 10^max(e,0) with 2^bits * 10^max(-e,0).
+ coeff := new(big.Int)
+ if !setCoeff(coeff, p.intPart, p.fracPart) || coeff.Sign() == 0 {
+ return false
+ }
+ lhs := coeff
+ rhs := new(big.Int).Set(twoPower(bits))
+ if e > 0 {
+ if e > maxDigits {
+ return true
+ }
+ lhs = new(big.Int).Mul(coeff, pow10(int(e)))
+ } else if e < 0 {
+ down := -e
+ if down > maxDigits {
+ return false
+ }
+ rhs.Mul(rhs, pow10(int(down)))
+ }
+ return lhs.Cmp(rhs) >= 0
+}
+
+func scaledExp(p Parsed, scale int64) (int64, bool) {
+ e, ok := add2(p.exp, scale)
+ if !ok {
+ return 0, false
+ }
+ return add2(e, -int64(len(p.fracPart)))
+}
+
+func decimalDigitsOfTwoPower(bits int) int {
+ switch bits {
+ case 32:
+ return 10
+ case 64:
+ return 20
+ case 127, 128:
+ return 39
+ case 255:
+ return 77
+ case 256:
+ return 78
+ default:
+ return int(math.Floor(float64(bits)*math.Log10(2))) + 1
+ }
+}
+
+func setCoeff(dst *big.Int, intPart, fracPart string) bool {
+ if len(fracPart) == 0 {
+ if isAllZeros(intPart) {
+ dst.SetInt64(0)
+ return true
+ }
+ _, ok := dst.SetString(intPart, 10)
+ return ok
+ }
+ if isAllZeros(intPart) {
+ if isAllZeros(fracPart) {
+ dst.SetInt64(0)
+ return true
+ }
+ _, ok := dst.SetString(fracPart, 10)
+ return ok
+ }
+ if _, ok := dst.SetString(intPart, 10); !ok {
+ return false
+ }
+ dst.Mul(dst, pow10(len(fracPart)))
+ if !isAllZeros(fracPart) {
+ var frac big.Int
+ if _, ok := frac.SetString(fracPart, 10); !ok {
+ return false
+ }
+ dst.Add(dst, &frac)
+ }
+ return true
+}
+
+func significantDigitCount(intPart, fracPart string) int {
+ i := 0
+ for i < len(intPart) && intPart[i] == '0' {
+ i++
+ }
+ if i < len(intPart) {
+ return len(intPart) - i + len(fracPart)
+ }
+ j := 0
+ for j < len(fracPart) && fracPart[j] == '0' {
+ j++
+ }
+ return len(fracPart) - j
+}
+
+func isAllZeros(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] != '0' {
+ return false
+ }
+ }
+ return true
+}
+
+func add2(a, b int64) (int64, bool) {
+ c := a + b
+ if (b > 0 && c < a) || (b < 0 && c > a) {
+ return 0, false
+ }
+ return c, true
+}
+
+var pt5 = big.NewFloat(0.5)
+
+// RoundScaled returns the integer nearest to scaled, with ties rounded away
+// from zero. scaled must hold the literal s multiplied by 10^scale; callers
+// use it to reject results that are too large before calling.
+//
+// The result is computed exactly from the digits of s when s is a plain
+// decimal literal, and from scaled otherwise.
+func RoundScaled(scaled *big.Float, s string, scale int64) *big.Int {
+ // A magnitude below 1/4 rounds to zero. Returning early skips the
+ // rounding below, which allocates in proportion to the gap between the
+ // value's exponent and 0.5's.
+ if scaled.MantExp(nil) < -1 {
+ return new(big.Int)
+ }
+ if val, ok := ScaleAndRound(s, scale); ok {
+ return val
+ }
+
+ out := new(big.Float).Copy(scaled)
+ if out.Signbit() {
+ out.Sub(out, pt5)
+ } else {
+ out.Add(out, pt5)
+ }
+ val, _ := out.Int(nil)
+ return val
+}
+
+func isDigit(c byte) bool { return '0' <= c && c <= '9' }
diff --git a/arrow/internal/decimalstr/decimalstr_test.go
b/arrow/internal/decimalstr/decimalstr_test.go
new file mode 100644
index 00000000..bf700b9c
--- /dev/null
+++ b/arrow/internal/decimalstr/decimalstr_test.go
@@ -0,0 +1,156 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package decimalstr_test
+
+import (
+ "math/big"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/apache/arrow-go/v18/arrow/internal/decimalstr"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestScaleAndRound(t *testing.T) {
+ tests := []struct {
+ s string
+ scale int64
+ expected string
+ }{
+ {"0.35", 1, "4"},
+ {"0.15", 1, "2"},
+ {"0.25", 1, "3"},
+ {"2.675", 2, "268"},
+ {"2.675", 1, "27"},
+ {"-0.35", 1, "-4"},
+ {"-0.15", 1, "-2"},
+ {"0.349999", 1, "3"},
+ {"0.5", 0, "1"},
+ {"-0.5", 0, "-1"},
+ {"0.49", 0, "0"},
+ {"-0.4", 0, "0"},
+ {"0.05", 0, "0"},
+ {"5e-1", 0, "1"},
+ {"35e-2", 1, "4"},
+ {"0.035E+1", 1, "4"},
+ {"+12.3", 1, "123"},
+ {"12.", 2, "1200"},
+ {".5", 0, "1"},
+ {"1.23e+3", 0, "1230"},
+ {"0000.000", 4, "0"},
+ {"-0", 0, "0"},
+ {"1e-50", 2, "0"},
+ {"12345678901234567890.5", 0, "12345678901234567891"},
+ {"1.00000000000000000000000000000000000005", 37,
"10000000000000000000000000000000000001"},
+ {"19", -1, "2"},
+ {"15", -1, "2"},
+ {"14", -1, "1"},
+ {"-15", -1, "-2"},
+ {"-19", -1, "-2"},
+ {"10", -1, "1"},
+ {"5", -1, "1"},
+ {"4", -1, "0"},
+ {"50", -2, "1"},
+ {"25", -2, "0"},
+ {"1e38", -38, "1"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.s, func(t *testing.T) {
+ got, ok := decimalstr.ScaleAndRound(tt.s, tt.scale)
+ require.True(t, ok)
+ assert.Equal(t, tt.expected, got.String())
+ })
+ }
+}
+
+func TestScaleAndRoundRejectsNonDecimal(t *testing.T) {
+ for _, s := range []string{"", "+", ".", "e5", "1e", "1e+", "1p3",
"inf", "-Inf", "NaN", "0x10", "1_000", "1/2", "1.2.3", " 1",
"1e99999999999999999999"} {
+ t.Run(s, func(t *testing.T) {
+ _, ok := decimalstr.ScaleAndRound(s, 2)
+ assert.False(t, ok)
+ })
+ }
+}
+
+func TestScaleAndRoundBoundsDigits(t *testing.T) {
+ _, ok := decimalstr.ScaleAndRound("1e5000", 0)
+ assert.False(t, ok)
+ _, ok = decimalstr.ScaleAndRound("1", 5000)
+ assert.False(t, ok)
+}
+
+func TestScaleAndRoundLongFraction(t *testing.T) {
+ // Only the first dropped digit decides the rounding, so the number of
+ // dropped fraction digits is not bounded.
+ tests := []struct {
+ s string
+ scale int64
+ expected string
+ }{
+ {"0." + strings.Repeat("7", 1000), 2, "78"},
+ {"0." + strings.Repeat("7", 1030), 2, "78"},
+ {"-0." + strings.Repeat("7", 5000), 2, "-78"},
+ {"0.12" + strings.Repeat("4", 2000), 2, "12"},
+ {"0.125" + strings.Repeat("0", 2000), 2, "13"},
+ {"0.124" + strings.Repeat("9", 2000), 2, "12"},
+ {"1." + strings.Repeat("9", 3000), 0, "2"},
+ {"12" + strings.Repeat("0", 1100) + "e-1100", -1, "1"},
+ {"0." + strings.Repeat("0", 1500) + "5", 2, "0"},
+ }
+ for i, tt := range tests {
+ t.Run(strconv.Itoa(i), func(t *testing.T) {
+ got, ok := decimalstr.ScaleAndRound(tt.s, tt.scale)
+ require.True(t, ok)
+ assert.Equal(t, tt.expected, got.String())
+ })
+ }
+}
+
+func TestRoundScaledFallsBackToFloat(t *testing.T) {
+ scaled := new(big.Float).SetFloat64(2.5)
+ // Not a decimal literal, so the float is rounded instead.
+ assert.Equal(t, "3", decimalstr.RoundScaled(scaled, "0x1.4p1",
0).String())
+ assert.Equal(t, "-3",
decimalstr.RoundScaled(new(big.Float).Neg(scaled), "-0x1.4p1", 0).String())
+ assert.Equal(t, "0",
decimalstr.RoundScaled(new(big.Float).SetFloat64(0.2), "0.2", 0).String())
+}
+
+func TestParsedAtLeastTwoPower(t *testing.T) {
+ mustParse := func(s string) decimalstr.Parsed {
+ t.Helper()
+ p, ok := decimalstr.Parse(s)
+ require.True(t, ok, s)
+ return p
+ }
+ assert.False(t, mustParse("19").AtLeastTwoPower(0, 127))
+ assert.False(t, mustParse("1e38").AtLeastTwoPower(0, 127))
+ assert.True(t, mustParse("1e40").AtLeastTwoPower(0, 127))
+ assert.False(t, mustParse("1.5e38").AtLeastTwoPower(0, 127))
+ assert.True(t, mustParse("1e1000000000").AtLeastTwoPower(0, 128))
+ assert.False(t, mustParse("-1e-20000000").AtLeastTwoPower(0, 127))
+ assert.False(t, mustParse("4294967295").AtLeastTwoPower(0, 32))
+ assert.True(t, mustParse("4294967296").AtLeastTwoPower(0, 32))
+ assert.True(t, mustParse("18446744073709551616").AtLeastTwoPower(0, 64))
+ assert.False(t, mustParse("9223372036854775808").AtLeastTwoPower(0, 64))
+}
+
+func TestScaleAndRoundTinyExponentDoesNotAllocate(t *testing.T) {
+ got, ok := decimalstr.ScaleAndRound("-1e-20000000", 0)
+ require.True(t, ok)
+ assert.Equal(t, "0", got.String())
+}