internal/encoding/text: format using 32 bitsize when encoding float32
When encoding/textpb marshals out float32 values, it was previously
formatting it as float64 bitsize since both float types are stored as
float64 and internal/encoding/text only has one Float type. A
consequence of this is that the output may display a different value
than expected, e.g. 1.02 becomes 1.0199999809265137.
This CL splits Float type into Float32 and Float64 to keep track of
which bitsize to use when formatting. Values of both types are still
stored as float64 to keep the logic simple.
Decoding will always use Float64, but users can ask for a float32 value
from it.
Change-Id: Iea5b14b283fec2236a0c3946fac34d4d79b95274
Reviewed-on: https://go-review.googlesource.com/c/158497
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/internal/encoding/text/text_test.go b/internal/encoding/text/text_test.go
index 2f2d140..7361e77 100644
--- a/internal/encoding/text/text_test.go
+++ b/internal/encoding/text/text_test.go
@@ -550,6 +550,10 @@
in: `crazy:"x'"'\""\''"'z"`,
wantVal: V(Msg{{ID("crazy"), V(`x'""''z`)}}),
}, {
+ in: `num: 1.02`,
+ wantVal: V(Msg{{ID("num"), V(float32(1.02))}}), // Use float32 to test marshaling of Float32 type.
+ wantOut: `num:1.02`,
+ }, {
in: `nums: [t,T,true,True,TRUE,f,F,false,False,FALSE]`,
wantVal: V(Msg{{ID("nums"), V(Lst{
V(true),
@@ -790,9 +794,16 @@
want, _ := x.Uint(true)
got, ok := y.Uint(math.MaxUint32 < want)
return got == want && ok
- case Float:
- want, _ := x.Float(true)
- got, ok := y.Float(math.MaxFloat32 < math.Abs(want))
+ case Float32:
+ want, _ := x.Float32()
+ got, ok := y.Float32()
+ if math.IsNaN(float64(got)) || math.IsNaN(float64(want)) {
+ return math.IsNaN(float64(got)) == math.IsNaN(float64(want))
+ }
+ return got == want && ok
+ case Float64:
+ want, _ := x.Float64()
+ got, ok := y.Float64()
if math.IsNaN(got) || math.IsNaN(want) {
return math.IsNaN(got) == math.IsNaN(want)
}