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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
|
// Copyright (C) 2022 Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later
package lowmemjson
import (
"fmt"
"io"
"unicode/utf8"
)
type reencodeState func(rune) error
type ReEncoder struct {
Out io.Writer
AllowMultipleValues bool
// Whether to minify the JSON.
Compact bool
// String to use to indent; ignored if Compact is true.
Indent string
// String to put before indents.
Prefix string
// Whether to emit a newline after each top-level value, even
// if it could unambiguously be omitted.
ForceTrailingNewlines bool
// Returns whether a given character in a string should be
// backslash-escaped. The bool argument is whether it was
// \u-escaped in the input. This does not affect characters
// that must or must-not be escaped to be valid JSON.
//
// If not set, then EscapeDefault is used.
BackslashEscape BackslashEscaper
// state: .Write's utf8-decoding buffer
buf [utf8.UTFMax]byte
bufLen int
// state: .WriteRune
err error
par Parser
written int
inputPos int64
// state: .handleRune
lastNonSpace RuneType
curIndent int
uhex [4]byte // "\uABCD"-encoded characters in strings
fracZeros int64
expZero bool
}
// public API //////////////////////////////////////////////////////////////////
func (enc *ReEncoder) Write(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
var n int
if enc.bufLen > 0 {
copy(enc.buf[enc.bufLen:], p)
c, size := utf8.DecodeRune(enc.buf[:])
n += size - enc.bufLen
enc.bufLen = 0
if _, err := enc.WriteRune(c); err != nil {
return 0, err
}
}
for utf8.FullRune(p[n:]) {
c, size := utf8.DecodeRune(p[n:])
if _, err := enc.WriteRune(c); err != nil {
return n, err
}
n += size
}
enc.bufLen = copy(enc.buf[:], p[n:])
return len(p), nil
}
func (enc *ReEncoder) Close() error {
if enc.bufLen > 0 {
return &ReEncodeSyntaxError{
Offset: enc.inputPos,
Err: fmt.Errorf("%w: unflushed unicode garbage: %q", io.ErrUnexpectedEOF, enc.buf[:enc.bufLen]),
}
}
if _, err := enc.par.HandleEOF(); err != nil {
enc.err = &ReEncodeSyntaxError{
Err: err,
Offset: enc.inputPos,
}
return enc.err
}
if err := enc.handleRune(0, 0); err != nil {
enc.err = &ReEncodeSyntaxError{
Err: err,
Offset: enc.inputPos,
}
return enc.err
}
if enc.AllowMultipleValues {
enc.par.Reset()
}
return nil
}
func (enc *ReEncoder) WriteRune(c rune) (n int, err error) {
if enc.err != nil {
return 0, enc.err
}
if enc.bufLen > 0 {
enc.err = fmt.Errorf("lowmemjson.ReEncoder: cannot .WriteRune() when there is a partial rune that has been .Write()en: %q", enc.buf[:enc.bufLen])
return 0, enc.err
}
enc.written = 0
rehandle:
t, err := enc.par.HandleRune(c)
if err != nil {
enc.err = &ReEncodeSyntaxError{
Err: err,
Offset: enc.inputPos,
}
return enc.written, enc.err
}
enc.err = enc.handleRune(c, t)
if enc.err == nil && t == RuneTypeEOF {
if enc.AllowMultipleValues {
enc.par.Reset()
goto rehandle
} else {
enc.err = &ReEncodeSyntaxError{
Err: fmt.Errorf("invalid character %q after top-level value", c),
Offset: enc.inputPos,
}
return enc.written, enc.err
}
}
enc.inputPos += int64(utf8.RuneLen(c))
return enc.written, enc.err
}
// internal ////////////////////////////////////////////////////////////////////
func (enc *ReEncoder) handleRune(c rune, t RuneType) error {
// whitespace
switch t {
case RuneTypeSpace:
if enc.Compact || enc.Indent != "" {
return nil
}
}
defer func() {
enc.lastNonSpace = t
}()
// shorten numbers
switch t { // trim trailing '0's from the fraction-part, but don't remove all digits
case RuneTypeNumberFracDot:
enc.fracZeros = 0
case RuneTypeNumberFracDig:
if c == '0' && enc.lastNonSpace == RuneTypeNumberFracDig {
enc.fracZeros++
return nil
}
fallthrough
default:
for enc.fracZeros > 0 {
if err := enc.emitByte('0'); err != nil {
return err
}
enc.fracZeros--
}
}
switch t { // trim leading '0's from the exponent-part, but don't remove all digits
case RuneTypeNumberExpE, RuneTypeNumberExpSign:
enc.expZero = true
case RuneTypeNumberExpDig:
if c == '0' && enc.expZero {
return nil
}
enc.expZero = false
default:
if enc.expZero {
if err := enc.emitByte('0'); err != nil {
return err
}
enc.expZero = false
}
}
// indent
switch t {
case RuneTypeObjectBeg, RuneTypeArrayBeg:
enc.curIndent++
case RuneTypeObjectEnd, RuneTypeArrayEnd:
enc.curIndent--
switch enc.lastNonSpace {
case RuneTypeObjectBeg, RuneTypeArrayBeg:
// collapse
default:
if err := enc.emitNlIndent(); err != nil {
return err
}
}
case RuneTypeObjectColon:
if !enc.Compact && enc.Indent != "" {
if err := enc.emitByte(':'); err != nil {
return err
}
return enc.emitByte(' ')
}
default:
switch enc.lastNonSpace {
case RuneTypeObjectBeg, RuneTypeObjectComma, RuneTypeArrayBeg, RuneTypeArrayComma:
if err := enc.emitNlIndent(); err != nil {
return err
}
}
}
// main
switch t {
case RuneTypeStringChar:
return enc.emit(writeStringChar(enc.Out, c, BackslashEscapeNone, enc.BackslashEscape))
case RuneTypeStringEsc, RuneTypeStringEscU:
return nil
case RuneTypeStringEsc1:
switch c {
case '"':
return enc.emit(writeStringChar(enc.Out, '"', BackslashEscapeShort, enc.BackslashEscape))
case '\\':
return enc.emit(writeStringChar(enc.Out, '\\', BackslashEscapeShort, enc.BackslashEscape))
case '/':
return enc.emit(writeStringChar(enc.Out, '/', BackslashEscapeShort, enc.BackslashEscape))
case 'b':
return enc.emit(writeStringChar(enc.Out, '\b', BackslashEscapeShort, enc.BackslashEscape))
case 'f':
return enc.emit(writeStringChar(enc.Out, '\f', BackslashEscapeShort, enc.BackslashEscape))
case 'n':
return enc.emit(writeStringChar(enc.Out, '\n', BackslashEscapeShort, enc.BackslashEscape))
case 'r':
return enc.emit(writeStringChar(enc.Out, '\r', BackslashEscapeShort, enc.BackslashEscape))
case 't':
return enc.emit(writeStringChar(enc.Out, '\t', BackslashEscapeShort, enc.BackslashEscape))
default:
panic("should not happen")
}
case RuneTypeStringEscUA:
enc.uhex[0], _ = hex2int(c)
return nil
case RuneTypeStringEscUB:
enc.uhex[1], _ = hex2int(c)
return nil
case RuneTypeStringEscUC:
enc.uhex[2], _ = hex2int(c)
return nil
case RuneTypeStringEscUD:
enc.uhex[3], _ = hex2int(c)
c := 0 |
rune(enc.uhex[0])<<12 |
rune(enc.uhex[1])<<8 |
rune(enc.uhex[2])<<4 |
rune(enc.uhex[3])<<0
return enc.emit(writeStringChar(enc.Out, c, BackslashEscapeUnicode, enc.BackslashEscape))
case RuneTypeEOF: // start of next top-level value
if !enc.ForceTrailingNewlines && (enc.Compact || enc.Indent == "") && !enc.lastNonSpace.IsNumber() {
return nil
}
return enc.emitByte('\n')
case RuneTypeError: // .Close()
if !enc.ForceTrailingNewlines {
return nil
}
return enc.emitByte('\n')
default:
return enc.emitByte(byte(c))
}
}
func (enc *ReEncoder) emitByte(c byte) error {
err := writeByte(enc.Out, c)
if err == nil {
enc.written++
}
return err
}
func (enc *ReEncoder) emit(n int, err error) error {
enc.written += n
return err
}
func (enc *ReEncoder) emitNlIndent() error {
if enc.Compact || enc.Indent == "" {
return nil
}
if err := enc.emitByte('\n'); err != nil {
return err
}
if enc.Prefix != "" {
if err := enc.emit(io.WriteString(enc.Out, enc.Prefix)); err != nil {
return err
}
}
for i := 0; i < enc.curIndent; i++ {
if err := enc.emit(io.WriteString(enc.Out, enc.Indent)); err != nil {
return err
}
}
return nil
}
|