diff options
author | Luke Shumaker <lukeshu@lukeshu.com> | 2023-02-07 14:01:44 -0700 |
---|---|---|
committer | Luke Shumaker <lukeshu@lukeshu.com> | 2023-02-10 14:09:56 -0700 |
commit | 483bbdc970b26d774ace39edfde8420aba53b742 (patch) | |
tree | ee5fcacbba4d4eb7c44e4cb1f35fb950f11aee1d /encode.go | |
parent | 480ccfd05a13ac36516c536a71203280a31b4d28 (diff) |
Sync borrowed code from Go 1.20
New tests mean encode.go and compat.go also need some bugfixes.
Diffstat (limited to 'encode.go')
-rw-r--r-- | encode.go | 18 |
1 files changed, 13 insertions, 5 deletions
@@ -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 |