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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
|
// 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.
//
// Trims all whitespace, except that it emits a newline
// between two *number* top-level values (or puts a newline
// after all top-level values if ForceTrailingNewlines).
//
// Trims superflous 0s from numbers.
Compact bool
// String to use to indent; ignored if Compact is true.
//
// Newlines are emitted *between* top-level values; a newline is
// not emitted after the *last* top-level value (unless
// ForceTrailingNewlines is on).
Indent string
// String to put before indents.
Prefix string
// Whether to emit a newline after each top-level value. See
// the comments on Compact and Indent for discussion of how
// this is different than the usual behavior.
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
wasNumber bool
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
}
// Close does what you'd expect, mostly.
//
// The *ReEncoder may continue to be written to with new JSON values
// if enc.AllowMultipleValues is set.
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, RuneTypeError); 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 {
err, shouldHandle := enc.handleRunePre(c, t)
if err != nil {
return err
}
if !shouldHandle {
return nil
}
return enc.handleRuneMain(c, t)
}
// handle buffered things that need to happen before the new rune
// itself is handled.
func (enc *ReEncoder) handleRunePre(c rune, t RuneType) (error, bool) {
// emit newlines between top-level values
if enc.lastNonSpace == RuneTypeEOF {
switch {
case enc.wasNumber && t.IsNumber():
if err := enc.emitByte('\n'); err != nil {
return err, false
}
case enc.Indent != "" && !enc.Compact:
if err := enc.emitByte('\n'); err != nil {
return err, false
}
}
}
// 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, false
}
fallthrough
default:
for enc.fracZeros > 0 {
if err := enc.emitByte('0'); err != nil {
return err, false
}
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, false
}
enc.expZero = false
default:
if enc.expZero {
if err := enc.emitByte('0'); err != nil {
return err, false
}
enc.expZero = false
}
}
// whitespace
switch {
case enc.Compact:
if t == RuneTypeSpace {
return nil, false
}
case enc.Indent != "":
switch t {
case RuneTypeSpace:
// let us manage whitespace
return nil, false
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, false
}
}
default:
switch enc.lastNonSpace {
case RuneTypeObjectBeg, RuneTypeObjectComma, RuneTypeArrayBeg, RuneTypeArrayComma:
if err := enc.emitNlIndent(); err != nil {
return err, false
}
}
}
if enc.lastNonSpace == RuneTypeObjectColon {
if err := enc.emitByte(' '); err != nil {
return err, false
}
}
}
return nil, true
}
// handle the new rune itself, not buffered things
func (enc *ReEncoder) handleRuneMain(c rune, t RuneType) error {
defer func() {
if t != RuneTypeSpace {
enc.lastNonSpace = t
}
}()
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 RuneTypeError: // EOF explicitly stated by .Close()
fallthrough
case RuneTypeEOF: // EOF implied by the start of the next top-level value
enc.wasNumber = enc.lastNonSpace.IsNumber()
switch {
case enc.ForceTrailingNewlines:
t = RuneTypeError // enc.lastNonSpace : an NL isn't needed (we already printed one)
return enc.emitByte('\n')
default:
t = RuneTypeEOF // enc.lastNonSpace : an NL *might* be needed
return nil
}
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 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
}
|