From 8463646eb00c73e8a79bb2c578195cfe61538af9 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Thu, 27 Aug 2020 21:01:53 +0900 Subject: [PATCH] Fix encoding for Indent/MarshalIndent --- encode_vm.go | 28 +++++++++++++++++++++------- indent.go | 6 ++++-- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/encode_vm.go b/encode_vm.go index 8714a4c..9efcb3b 100644 --- a/encode_vm.go +++ b/encode_vm.go @@ -147,12 +147,22 @@ func (e *Encoder) run(code *opcode) error { ) } var buf bytes.Buffer - if err := compact(&buf, b, true); err != nil { - return err + if e.enabledIndent { + if err := encodeWithIndent( + &buf, + b, + string(e.prefix)+string(bytes.Repeat(e.indentStr, code.indent)), + string(e.indentStr), + ); err != nil { + return err + } + } else { + if err := compact(&buf, b, true); err != nil { + return err + } } e.encodeBytes(buf.Bytes()) code = code.next - code.ptr = ptr case opMarshalText: ptr := code.ptr isPtr := code.typ.Kind() == reflect.Ptr @@ -276,7 +286,7 @@ func (e *Encoder) run(code *opcode) error { } else { e.encodeByte('\n') e.encodeIndent(code.indent) - e.encodeBytes([]byte{']'}) + e.encodeByte(']') code = c.end.next } case opArrayHead: @@ -1352,15 +1362,19 @@ func (e *Encoder) run(code *opcode) error { field := code.toStructFieldCode() ptr := field.ptr if ptr == 0 { - e.encodeIndent(code.indent) - e.encodeNull() + if code.op == opStructFieldPtrHeadIntIndent { + e.encodeIndent(code.indent) + e.encodeNull() + } else { + e.encodeBytes([]byte{'{', '}'}) + } code = field.end } else { e.encodeBytes([]byte{'{', '\n'}) e.encodeIndent(code.indent + 1) e.encodeBytes(field.key) e.encodeByte(' ') - e.encodeInt(e.ptrToInt(ptr)) + e.encodeInt(e.ptrToInt(ptr + field.offset)) field.nextField.ptr = ptr code = field.next } diff --git a/indent.go b/indent.go index fc46ca8..a6a0329 100644 --- a/indent.go +++ b/indent.go @@ -52,9 +52,10 @@ func encodeWithIndent(dst *bytes.Buffer, src []byte, prefix, indentStr string) e if indentNum < 0 { return errInvalidCharacter('}', "}", cursor) } - b := []byte{'\n', c} + b := []byte{'\n'} b = append(b, prefix...) b = append(b, bytes.Repeat(indentBytes, indentNum)...) + b = append(b, c) if _, err := dst.Write(b); err != nil { return err } @@ -78,9 +79,10 @@ func encodeWithIndent(dst *bytes.Buffer, src []byte, prefix, indentStr string) e if indentNum < 0 { return errInvalidCharacter(']', "]", cursor) } - b := []byte{'\n', c} + b := []byte{'\n'} b = append(b, prefix...) b = append(b, bytes.Repeat(indentBytes, indentNum)...) + b = append(b, c) if _, err := dst.Write(b); err != nil { return err }