summaryrefslogtreecommitdiff
path: root/encode.go
diff options
context:
space:
mode:
Diffstat (limited to 'encode.go')
-rw-r--r--encode.go18
1 files changed, 13 insertions, 5 deletions
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