summaryrefslogtreecommitdiff
path: root/compat/json
diff options
context:
space:
mode:
Diffstat (limited to 'compat/json')
-rw-r--r--compat/json/compat.go61
1 files changed, 37 insertions, 24 deletions
diff --git a/compat/json/compat.go b/compat/json/compat.go
index 37a0d5b..8dcb266 100644
--- a/compat/json/compat.go
+++ b/compat/json/compat.go
@@ -71,40 +71,46 @@ func Marshal(v any) ([]byte, error) {
}
type Encoder struct {
- inner lowmemjson.ReEncoder
+ encoder lowmemjson.Encoder
+ formatter lowmemjson.ReEncoder
}
func NewEncoder(w io.Writer) *Encoder {
- return &Encoder{
- inner: lowmemjson.ReEncoder{
- Out: w,
- Compact: true,
+ ret := &Encoder{
+ formatter: lowmemjson.ReEncoder{
+ Out: w,
+
+ AllowMultipleValues: true,
+
+ Compact: true,
+ ForceTrailingNewlines: true,
},
}
+ ret.encoder.W = &ret.formatter
+ return ret
}
func (enc *Encoder) Encode(v any) error {
- if err := convertEncodeError(lowmemjson.Encode(&enc.inner, v)); err != nil {
- return err
- }
- if err := convertEncodeError(enc.inner.Close()); err != nil {
- return err
+ err := enc.encoder.Encode(v)
+ if err == nil {
+ err = enc.formatter.Close()
}
- return nil
+ return convertEncodeError(err)
}
func (enc *Encoder) SetEscapeHTML(on bool) {
- if on {
- enc.inner.BackslashEscape = nil
- } else {
- enc.inner.BackslashEscape = lowmemjson.EscapeJSSafe
+ var escaper lowmemjson.BackslashEscaper
+ if !on {
+ escaper = lowmemjson.EscapeDefaultNonHTMLSafe
}
+ enc.encoder.BackslashEscape = escaper
+ enc.formatter.BackslashEscape = escaper
}
func (enc *Encoder) SetIndent(prefix, indent string) {
- enc.inner.Compact = prefix == "" && indent == ""
- enc.inner.Prefix = prefix
- enc.inner.Indent = indent
+ enc.formatter.Compact = prefix == "" && indent == ""
+ enc.formatter.Prefix = prefix
+ enc.formatter.Indent = indent
}
// ReEncode wrappers /////////////////////////////////////////////////
@@ -169,12 +175,19 @@ func convertDecodeError(err error) error {
if derr, ok := err.(*lowmemjson.DecodeError); ok {
switch terr := derr.Err.(type) {
case *lowmemjson.DecodeSyntaxError:
- err = &SyntaxError{
- msg: terr.Err.Error(),
- Offset: terr.Offset,
- }
- if errors.Is(terr.Err, io.ErrUnexpectedEOF) {
- err.(*SyntaxError).msg = "unexpected end of JSON input"
+ switch {
+ case errors.Is(terr.Err, io.EOF):
+ err = io.EOF
+ case errors.Is(terr.Err, io.ErrUnexpectedEOF):
+ err = &SyntaxError{
+ msg: "unexpected end of JSON input",
+ Offset: terr.Offset,
+ }
+ default:
+ err = &SyntaxError{
+ msg: terr.Err.Error(),
+ Offset: terr.Offset,
+ }
}
case *lowmemjson.DecodeTypeError:
if typeErr, ok := terr.Err.(*json.UnmarshalTypeError); ok {