From 483bbdc970b26d774ace39edfde8420aba53b742 Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Tue, 7 Feb 2023 14:01:44 -0700 Subject: Sync borrowed code from Go 1.20 New tests mean encode.go and compat.go also need some bugfixes. --- encode.go | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) (limited to 'encode.go') diff --git a/encode.go b/encode.go index fa558b9..2d16891 100644 --- a/encode.go +++ b/encode.go @@ -40,8 +40,8 @@ type Encodable interface { // lowmemjson/compat/json.Encoder offers those .SetEscapeHTML and // .SetIndent methods. type Encoder struct { - w *ReEncoder - closeAfterEncode bool + w *ReEncoder + isRoot bool } // NewEncoder returns a new Encoder that writes to w. @@ -60,8 +60,8 @@ func NewEncoder(w io.Writer) *Encoder { }) } return &Encoder{ - w: re, - closeAfterEncode: re.par.StackIsEmpty(), + w: re, + isRoot: re.par.StackIsEmpty(), } } @@ -73,12 +73,20 @@ func NewEncoder(w io.Writer) *Encoder { // that, with the exception that in addition to the json.Marshaler // interface it also checks for the Encodable interface. // +// Unlike encoding/json.Encoder.Encode, lowmemjson.Encoder.Encode does +// not buffer its output; if a encode-error is encountered, lowmemjson +// may write partial output, whereas encodin/json would not have +// written anything. +// // [documentation for encoding/json.Marshal]: https://pkg.go.dev/encoding/json@go1.18#Marshal func (enc *Encoder) Encode(obj any) (err error) { + if enc.isRoot { + enc.w.par.Reset() + } if err := encode(enc.w, reflect.ValueOf(obj), enc.w.BackslashEscape, false, 0, map[any]struct{}{}); err != nil { return err } - if enc.closeAfterEncode { + if enc.isRoot { return enc.w.Close() } return nil -- cgit v1.2.3-2-g168b