Skip to content

Commit

Permalink
json: Fix encoding complex with negative i (#1001)
Browse files Browse the repository at this point in the history
Fix encoding of complex numbers with negative imaginary components.
Previously, `2 - 3i` was encoded as the following:

    2+-3i

Instead of the following:

    2-3i

Fix this by handling negative imaginary components correctly.

Fixes #995
  • Loading branch information
hemantjadon committed Sep 8, 2021
1 parent d8fd848 commit 914c4ff
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
6 changes: 5 additions & 1 deletion zapcore/json_encoder.go
Expand Up @@ -228,7 +228,11 @@ func (enc *jsonEncoder) AppendComplex128(val complex128) {
// Because we're always in a quoted string, we can use strconv without
// special-casing NaN and +/-Inf.
enc.buf.AppendFloat(r, 64)
enc.buf.AppendByte('+')
// If imaginary part is less than 0, minus (-) sign is added by default
// by AppendFloat.
if i >= 0 {
enc.buf.AppendByte('+')
}
enc.buf.AppendFloat(i, 64)
enc.buf.AppendByte('i')
enc.buf.AppendByte('"')
Expand Down
2 changes: 2 additions & 0 deletions zapcore/json_encoder_test.go
Expand Up @@ -64,6 +64,7 @@ func TestJSONEncodeEntry(t *testing.T) {
"so": "passes",
"answer": 42,
"common_pie": 3.14,
"complex_value": "3.14-2.71i",
"null_value": null,
"array_with_null_elements": [{}, null, null, 2],
"such": {
Expand All @@ -86,6 +87,7 @@ func TestJSONEncodeEntry(t *testing.T) {
zap.String("so", "passes"),
zap.Int("answer", 42),
zap.Float64("common_pie", 3.14),
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
// correct results for both the nil static interface{} value
Expand Down

0 comments on commit 914c4ff

Please sign in to comment.