summaryrefslogtreecommitdiff
path: root/encode.go
diff options
context:
space:
mode:
Diffstat (limited to 'encode.go')
-rw-r--r--encode.go11
1 files changed, 8 insertions, 3 deletions
diff --git a/encode.go b/encode.go
index 44fd985..f93cba4 100644
--- a/encode.go
+++ b/encode.go
@@ -40,7 +40,8 @@ func encodeWriteString(w io.Writer, str string) {
}
type Encoder struct {
- w *ReEncoder
+ w *ReEncoder
+ closeAfterEncode bool
}
// NewEncoder returns a new encoder.
@@ -57,7 +58,8 @@ func NewEncoder(w io.Writer) *Encoder {
}
}
return &Encoder{
- w: re,
+ w: re,
+ closeAfterEncode: len(re.par.stack) == 0 || (len(re.par.stack) == 1 && re.par.stack[0] == RuneTypeError),
}
}
@@ -72,7 +74,10 @@ func (enc *Encoder) Encode(obj any) (err error) {
}
}()
encode(enc.w, reflect.ValueOf(obj), enc.w.BackslashEscape, false, 0, map[any]struct{}{})
- return enc.w.Close()
+ if enc.closeAfterEncode {
+ return enc.w.Close()
+ }
+ return nil
}
// Encode encodes a value to w.