1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
|
// Copyright (C) 2022-2023 Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later
// Package json is a wrapper around lowmemjson that is a (mostly)
// drop-in replacement for the standard library's encoding/json.
package json
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"io"
"strconv"
"git.lukeshu.com/go/lowmemjson"
)
//nolint:stylecheck // ST1021 False positive; these aren't comments on individual types.
type (
Number = json.Number
RawMessage = json.RawMessage
Marshaler = json.Marshaler
Unmarshaler = json.Unmarshaler
// low-level decode errors.
UnmarshalTypeError = json.UnmarshalTypeError
// SyntaxError = json.SyntaxError // Duplicated to access a private field.
// high-level decode errors.
InvalidUnmarshalError = json.InvalidUnmarshalError
// marshal errors.
UnsupportedTypeError = json.UnsupportedTypeError
UnsupportedValueError = json.UnsupportedValueError
// MarshalerError = json.MarshalerError // Duplicated to access a private field.
)
// Encode wrappers ///////////////////////////////////////////////////
func convertEncodeError(err error) error {
if me, ok := err.(*lowmemjson.EncodeMethodError); ok {
err = &MarshalerError{
Type: me.Type,
Err: me.Err,
sourceFunc: me.SourceFunc,
}
}
return err
}
func marshal(v any, cfg lowmemjson.ReEncoderConfig) ([]byte, error) {
var buf bytes.Buffer
if err := convertEncodeError(lowmemjson.NewEncoder(lowmemjson.NewReEncoder(&buf, cfg)).Encode(v)); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func MarshalIndent(v any, prefix, indent string) ([]byte, error) {
return marshal(v, lowmemjson.ReEncoderConfig{
Indent: indent,
Prefix: prefix,
})
}
func Marshal(v any) ([]byte, error) {
return marshal(v, lowmemjson.ReEncoderConfig{
Compact: true,
})
}
type Encoder struct {
out io.Writer
buf bytes.Buffer
encoder *lowmemjson.Encoder
formatter *lowmemjson.ReEncoder
}
func NewEncoder(w io.Writer) *Encoder {
ret := &Encoder{
out: w,
}
ret.formatter = lowmemjson.NewReEncoder(&ret.buf, lowmemjson.ReEncoderConfig{
AllowMultipleValues: true,
Compact: true,
ForceTrailingNewlines: true,
})
ret.encoder = lowmemjson.NewEncoder(ret.formatter)
return ret
}
func (enc *Encoder) Encode(v any) error {
if err := convertEncodeError(enc.encoder.Encode(v)); err != nil {
enc.buf.Reset()
return err
}
if _, err := enc.buf.WriteTo(enc.out); err != nil {
return err
}
return nil
}
func (enc *Encoder) SetEscapeHTML(on bool) {
var escaper lowmemjson.BackslashEscaper
if !on {
escaper = lowmemjson.EscapeDefaultNonHTMLSafe
}
enc.formatter.BackslashEscape = escaper
}
func (enc *Encoder) SetIndent(prefix, indent string) {
enc.formatter.Compact = prefix == "" && indent == ""
enc.formatter.Prefix = prefix
enc.formatter.Indent = indent
}
// ReEncode wrappers /////////////////////////////////////////////////
func convertReEncodeError(err error) error {
if se, ok := err.(*lowmemjson.ReEncodeSyntaxError); ok {
err = &SyntaxError{
msg: se.Err.Error(),
Offset: se.Offset + 1,
}
if errors.Is(se.Err, io.ErrUnexpectedEOF) {
err.(*SyntaxError).msg = "unexpected end of JSON input"
}
}
return err
}
func HTMLEscape(dst *bytes.Buffer, src []byte) {
_, _ = lowmemjson.NewReEncoder(dst, lowmemjson.ReEncoderConfig{}).Write(src)
}
func reencode(dst io.Writer, src []byte, cfg lowmemjson.ReEncoderConfig) error {
formatter := lowmemjson.NewReEncoder(dst, cfg)
_, err := formatter.Write(src)
if err == nil {
err = formatter.Close()
}
return convertReEncodeError(err)
}
func Compact(dst *bytes.Buffer, src []byte) error {
return reencode(dst, src, lowmemjson.ReEncoderConfig{
Compact: true,
BackslashEscape: lowmemjson.EscapePreserve,
})
}
func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
return reencode(dst, src, lowmemjson.ReEncoderConfig{
Indent: indent,
Prefix: prefix,
BackslashEscape: lowmemjson.EscapePreserve,
})
}
func Valid(data []byte) bool {
formatter := lowmemjson.NewReEncoder(io.Discard, lowmemjson.ReEncoderConfig{
Compact: true,
})
_, err := formatter.Write(data)
return err == nil
}
// Decode wrappers ///////////////////////////////////////////////////
func convertDecodeError(err error) error {
if derr, ok := err.(*lowmemjson.DecodeError); ok {
switch terr := derr.Err.(type) {
case *lowmemjson.DecodeSyntaxError:
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 + 1,
}
}
case *lowmemjson.DecodeTypeError:
if typeErr, ok := terr.Err.(*json.UnmarshalTypeError); ok {
err = &UnmarshalTypeError{
Value: typeErr.Value,
Type: typeErr.Type,
Offset: typeErr.Offset,
Struct: derr.FieldParent,
Field: derr.FieldName,
}
} else if _, isArgErr := terr.Err.(*lowmemjson.DecodeArgumentError); terr.Err != nil &&
!isArgErr &&
!errors.Is(terr.Err, lowmemjson.ErrDecodeNonEmptyInterface) &&
!errors.Is(terr.Err, strconv.ErrSyntax) &&
!errors.Is(terr.Err, strconv.ErrRange) {
err = terr.Err
} else {
err = &UnmarshalTypeError{
Value: terr.JSONType,
Type: terr.GoType,
Offset: terr.Offset,
Struct: derr.FieldParent,
Field: derr.FieldName,
}
}
}
}
return err
}
func Unmarshal(data []byte, ptr any) error {
return convertDecodeError(lowmemjson.NewDecoder(bytes.NewReader(data)).DecodeThenEOF(ptr))
}
type Decoder struct {
*lowmemjson.Decoder
buf *bufio.Reader
}
func NewDecoder(r io.Reader) *Decoder {
br, ok := r.(*bufio.Reader)
if !ok {
br = bufio.NewReader(r)
}
return &Decoder{
Decoder: lowmemjson.NewDecoder(br),
buf: br,
}
}
func (dec *Decoder) Decode(ptr any) error {
return convertDecodeError(dec.Decoder.Decode(ptr))
}
func (dec *Decoder) Buffered() io.Reader {
dat, _ := dec.buf.Peek(dec.buf.Buffered())
return bytes.NewReader(dat)
}
// func (dec *Decoder) Token() (Token, error)
|