Commit abaf0cb5e2 for golang
commit abaf0cb5e2eaf4e095f2f56ff425003d8a588501
Author: Guido Iaquinti <guido.iaquinti@gmail.com>
Date: Tue Dec 1 18:06:04 2026 +0000
math/big: make Parse consistently return nil Float on error with trailing input
Float.Parse saves the Float from a successful prefix scan. If a
trailing byte is present, it reports an error and returns that Float.
ParseFloat inherits the result through Float.Parse.
Return a nil Float when the end-of-input check reports an error.
Preserve the detected base and the error.
Fixes #83483.
Change-Id: I9e5b5420edbafc33c22951671cef3a8987d6f526
GitHub-Last-Rev: 0cd3c72879cbaa7b7e4f952f32ca6b5097395af0
GitHub-Pull-Request: golang/go#83484
Reviewed-on: https://go-review.googlesource.com/c/go/+/868104
Auto-Submit: Robert Griesemer <gri@google.com>
Reviewed-by: Emmanuel Odeke <emmanuel@orijtech.com>
Reviewed-by: Keith Randall <khr@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Robert Griesemer <gri@google.com>
diff --git a/src/math/big/floatconv.go b/src/math/big/floatconv.go
index d8c69b8b28..7f2ea941df 100644
--- a/src/math/big/floatconv.go
+++ b/src/math/big/floatconv.go
@@ -274,8 +274,10 @@ func (z *Float) Parse(s string, base int) (f *Float, b int, err error) {
// entire string must have been consumed
if ch, err2 := r.ReadByte(); err2 == nil {
+ f = nil
err = fmt.Errorf("expected end of string, found %q", ch)
} else if err2 != io.EOF {
+ f = nil
err = err2
}
diff --git a/src/math/big/floatconv_test.go b/src/math/big/floatconv_test.go
index 726ce90615..53d5ff3466 100644
--- a/src/math/big/floatconv_test.go
+++ b/src/math/big/floatconv_test.go
@@ -191,6 +191,26 @@ func TestFloatSetFloat64String(t *testing.T) {
}
}
+func TestFloatParseTrailingInput(t *testing.T) {
+ for _, test := range []struct {
+ s string
+ base, wantBase int
+ }{
+ {"1!", 10, 10},
+ {"0x1p2!", 0, 16},
+ } {
+ var z Float
+ f, b, err := z.Parse(test.s, test.base)
+ if f != nil || b != test.wantBase || err == nil {
+ t.Errorf("Float.Parse(%q, %d) = (%v, %d, %v), want (nil, %d, error)", test.s, test.base, f, b, err, test.wantBase)
+ }
+ f, b, err = ParseFloat(test.s, test.base, 64, ToNearestEven)
+ if f != nil || b != test.wantBase || err == nil {
+ t.Errorf("ParseFloat(%q, %d, 64, ToNearestEven) = (%v, %d, %v), want (nil, %d, error)", test.s, test.base, f, b, err, test.wantBase)
+ }
+ }
+}
+
func fdiv(a, b float64) float64 { return a / b }
const (