Fix encoding for Indent/MarshalIndent

This commit is contained in:
Masaaki Goshima 2020-08-27 21:01:53 +09:00
parent 15b28f80fd
commit 8463646eb0
2 changed files with 25 additions and 9 deletions

View File

@ -147,12 +147,22 @@ func (e *Encoder) run(code *opcode) error {
)
}
var buf bytes.Buffer
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 {
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
}

View File

@ -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
}