From 305c249974e46e5f60704efc2911a04fa4ba9f55 Mon Sep 17 00:00:00 2001 From: Manjari Akella Date: Wed, 8 Sep 2021 13:28:53 -0700 Subject: [PATCH] json: Fix float32 encoding and add test (#1003) This commit fixes incorrect float32 encoding. A test case is also added. Refs: * https://github.com/uber-go/zap/issues/1002 * Internal ticket: GO-860 --- zapcore/json_encoder.go | 6 +++++- zapcore/json_encoder_test.go | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/zapcore/json_encoder.go b/zapcore/json_encoder.go index 47c05cdc1..af220d9b4 100644 --- a/zapcore/json_encoder.go +++ b/zapcore/json_encoder.go @@ -128,6 +128,11 @@ func (enc *jsonEncoder) AddFloat64(key string, val float64) { enc.AppendFloat64(val) } +func (enc *jsonEncoder) AddFloat32(key string, val float32) { + enc.addKey(key) + enc.AppendFloat32(val) +} + func (enc *jsonEncoder) AddInt64(key string, val int64) { enc.addKey(key) enc.AppendInt64(val) @@ -297,7 +302,6 @@ func (enc *jsonEncoder) AppendUint64(val uint64) { } func (enc *jsonEncoder) AddComplex64(k string, v complex64) { enc.AddComplex128(k, complex128(v)) } -func (enc *jsonEncoder) AddFloat32(k string, v float32) { enc.AddFloat64(k, float64(v)) } func (enc *jsonEncoder) AddInt(k string, v int) { enc.AddInt64(k, int64(v)) } func (enc *jsonEncoder) AddInt32(k string, v int32) { enc.AddInt64(k, int64(v)) } func (enc *jsonEncoder) AddInt16(k string, v int16) { enc.AddInt64(k, int64(v)) } diff --git a/zapcore/json_encoder_test.go b/zapcore/json_encoder_test.go index c797b6187..8e82c1a7a 100644 --- a/zapcore/json_encoder_test.go +++ b/zapcore/json_encoder_test.go @@ -63,6 +63,7 @@ func TestJSONEncodeEntry(t *testing.T) { "M": "lob law", "so": "passes", "answer": 42, + "a_float32": 2.71, "common_pie": 3.14, "complex_value": "3.14-2.71i", "null_value": null, @@ -87,6 +88,7 @@ func TestJSONEncodeEntry(t *testing.T) { zap.String("so", "passes"), zap.Int("answer", 42), zap.Float64("common_pie", 3.14), + zap.Float32("a_float32", 2.71), zap.Complex128("complex_value", 3.14-2.71i), // Cover special-cased handling of nil in AddReflect() and // AppendReflect(). Note that for the latter, we explicitly test