1
2
3
4
5 package json
6
7 import (
8 "bytes"
9 "errors"
10 "io"
11 )
12
13
14 type Decoder struct {
15 r io.Reader
16 buf []byte
17 d decodeState
18 scanp int
19 scanned int64
20 scan scanner
21 err error
22
23 tokenState int
24 tokenStack []int
25 }
26
27
28
29
30
31 func NewDecoder(r io.Reader) *Decoder {
32 return &Decoder{r: r}
33 }
34
35
36
37 func (dec *Decoder) UseNumber() { dec.d.useNumber = true }
38
39
40
41
42 func (dec *Decoder) DisallowUnknownFields() { dec.d.disallowUnknownFields = true }
43
44
45
46
47
48
49 func (dec *Decoder) Decode(v any) error {
50 if dec.err != nil {
51 return dec.err
52 }
53
54 if err := dec.tokenPrepareForDecode(); err != nil {
55 return err
56 }
57
58 if !dec.tokenValueAllowed() {
59 return &SyntaxError{msg: "not at beginning of value", Offset: dec.InputOffset()}
60 }
61
62
63 n, err := dec.readValue()
64 if err != nil {
65 return err
66 }
67 dec.d.init(dec.buf[dec.scanp : dec.scanp+n])
68 dec.scanp += n
69
70
71
72
73 err = dec.d.unmarshal(v)
74
75
76 dec.tokenValueEnd()
77
78 return err
79 }
80
81
82
83 func (dec *Decoder) Buffered() io.Reader {
84 return bytes.NewReader(dec.buf[dec.scanp:])
85 }
86
87
88
89 func (dec *Decoder) readValue() (int, error) {
90 dec.scan.reset()
91
92 scanp := dec.scanp
93 var err error
94 Input:
95
96
97 for scanp >= 0 {
98
99
100 for ; scanp < len(dec.buf); scanp++ {
101 c := dec.buf[scanp]
102 dec.scan.bytes++
103 switch dec.scan.step(&dec.scan, c) {
104 case scanEnd:
105
106
107
108 dec.scan.bytes--
109 break Input
110 case scanEndObject, scanEndArray:
111
112
113
114 if stateEndValue(&dec.scan, ' ') == scanEnd {
115 scanp++
116 break Input
117 }
118 case scanError:
119 dec.err = dec.scan.err
120 return 0, dec.scan.err
121 }
122 }
123
124
125
126 if err != nil {
127 if err == io.EOF {
128 if dec.scan.step(&dec.scan, ' ') == scanEnd {
129 break Input
130 }
131 if nonSpace(dec.buf) {
132 err = io.ErrUnexpectedEOF
133 }
134 }
135 dec.err = err
136 return 0, err
137 }
138
139 n := scanp - dec.scanp
140 err = dec.refill()
141 scanp = dec.scanp + n
142 }
143 return scanp - dec.scanp, nil
144 }
145
146 func (dec *Decoder) refill() error {
147
148
149 if dec.scanp > 0 {
150 dec.scanned += int64(dec.scanp)
151 n := copy(dec.buf, dec.buf[dec.scanp:])
152 dec.buf = dec.buf[:n]
153 dec.scanp = 0
154 }
155
156
157 const minRead = 512
158 if cap(dec.buf)-len(dec.buf) < minRead {
159 newBuf := make([]byte, len(dec.buf), 2*cap(dec.buf)+minRead)
160 copy(newBuf, dec.buf)
161 dec.buf = newBuf
162 }
163
164
165 n, err := dec.r.Read(dec.buf[len(dec.buf):cap(dec.buf)])
166 dec.buf = dec.buf[0 : len(dec.buf)+n]
167
168 return err
169 }
170
171 func nonSpace(b []byte) bool {
172 for _, c := range b {
173 if !isSpace(c) {
174 return true
175 }
176 }
177 return false
178 }
179
180
181 type Encoder struct {
182 w io.Writer
183 err error
184 escapeHTML bool
185
186 indentBuf []byte
187 indentPrefix string
188 indentValue string
189 }
190
191
192 func NewEncoder(w io.Writer) *Encoder {
193 return &Encoder{w: w, escapeHTML: true}
194 }
195
196
197
198
199
200
201 func (enc *Encoder) Encode(v any) error {
202 if enc.err != nil {
203 return enc.err
204 }
205
206 e := newEncodeState()
207 defer encodeStatePool.Put(e)
208
209 err := e.marshal(v, encOpts{escapeHTML: enc.escapeHTML})
210 if err != nil {
211 return err
212 }
213
214
215
216
217
218
219
220 e.WriteByte('\n')
221
222 b := e.Bytes()
223 if enc.indentPrefix != "" || enc.indentValue != "" {
224 enc.indentBuf, err = appendIndent(enc.indentBuf[:0], b, enc.indentPrefix, enc.indentValue)
225 if err != nil {
226 return err
227 }
228 b = enc.indentBuf
229 }
230 if _, err = enc.w.Write(b); err != nil {
231 enc.err = err
232 }
233 return err
234 }
235
236
237
238
239 func (enc *Encoder) SetIndent(prefix, indent string) {
240 enc.indentPrefix = prefix
241 enc.indentValue = indent
242 }
243
244
245
246
247
248
249
250
251 func (enc *Encoder) SetEscapeHTML(on bool) {
252 enc.escapeHTML = on
253 }
254
255
256
257
258 type RawMessage []byte
259
260
261 func (m RawMessage) MarshalJSON() ([]byte, error) {
262 if m == nil {
263 return []byte("null"), nil
264 }
265 return m, nil
266 }
267
268
269 func (m *RawMessage) UnmarshalJSON(data []byte) error {
270 if m == nil {
271 return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
272 }
273 *m = append((*m)[0:0], data...)
274 return nil
275 }
276
277 var _ Marshaler = (*RawMessage)(nil)
278 var _ Unmarshaler = (*RawMessage)(nil)
279
280
281
282
283
284
285
286
287
288 type Token any
289
290 const (
291 tokenTopValue = iota
292 tokenArrayStart
293 tokenArrayValue
294 tokenArrayComma
295 tokenObjectStart
296 tokenObjectKey
297 tokenObjectColon
298 tokenObjectValue
299 tokenObjectComma
300 )
301
302
303 func (dec *Decoder) tokenPrepareForDecode() error {
304
305
306
307 switch dec.tokenState {
308 case tokenArrayComma:
309 c, err := dec.peek()
310 if err != nil {
311 return err
312 }
313 if c != ',' {
314 return &SyntaxError{"expected comma after array element", dec.InputOffset()}
315 }
316 dec.scanp++
317 dec.tokenState = tokenArrayValue
318 case tokenObjectColon:
319 c, err := dec.peek()
320 if err != nil {
321 return err
322 }
323 if c != ':' {
324 return &SyntaxError{"expected colon after object key", dec.InputOffset()}
325 }
326 dec.scanp++
327 dec.tokenState = tokenObjectValue
328 }
329 return nil
330 }
331
332 func (dec *Decoder) tokenValueAllowed() bool {
333 switch dec.tokenState {
334 case tokenTopValue, tokenArrayStart, tokenArrayValue, tokenObjectValue:
335 return true
336 }
337 return false
338 }
339
340 func (dec *Decoder) tokenValueEnd() {
341 switch dec.tokenState {
342 case tokenArrayStart, tokenArrayValue:
343 dec.tokenState = tokenArrayComma
344 case tokenObjectValue:
345 dec.tokenState = tokenObjectComma
346 }
347 }
348
349
350 type Delim rune
351
352 func (d Delim) String() string {
353 return string(d)
354 }
355
356
357
358
359
360
361
362
363
364
365
366
367 func (dec *Decoder) Token() (Token, error) {
368 for {
369 c, err := dec.peek()
370 if err != nil {
371 return nil, err
372 }
373 switch c {
374 case '[':
375 if !dec.tokenValueAllowed() {
376 return dec.tokenError(c)
377 }
378 dec.scanp++
379 dec.tokenStack = append(dec.tokenStack, dec.tokenState)
380 dec.tokenState = tokenArrayStart
381 return Delim('['), nil
382
383 case ']':
384 if dec.tokenState != tokenArrayStart && dec.tokenState != tokenArrayComma {
385 return dec.tokenError(c)
386 }
387 dec.scanp++
388 dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1]
389 dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1]
390 dec.tokenValueEnd()
391 return Delim(']'), nil
392
393 case '{':
394 if !dec.tokenValueAllowed() {
395 return dec.tokenError(c)
396 }
397 dec.scanp++
398 dec.tokenStack = append(dec.tokenStack, dec.tokenState)
399 dec.tokenState = tokenObjectStart
400 return Delim('{'), nil
401
402 case '}':
403 if dec.tokenState != tokenObjectStart && dec.tokenState != tokenObjectComma {
404 return dec.tokenError(c)
405 }
406 dec.scanp++
407 dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1]
408 dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1]
409 dec.tokenValueEnd()
410 return Delim('}'), nil
411
412 case ':':
413 if dec.tokenState != tokenObjectColon {
414 return dec.tokenError(c)
415 }
416 dec.scanp++
417 dec.tokenState = tokenObjectValue
418 continue
419
420 case ',':
421 if dec.tokenState == tokenArrayComma {
422 dec.scanp++
423 dec.tokenState = tokenArrayValue
424 continue
425 }
426 if dec.tokenState == tokenObjectComma {
427 dec.scanp++
428 dec.tokenState = tokenObjectKey
429 continue
430 }
431 return dec.tokenError(c)
432
433 case '"':
434 if dec.tokenState == tokenObjectStart || dec.tokenState == tokenObjectKey {
435 var x string
436 old := dec.tokenState
437 dec.tokenState = tokenTopValue
438 err := dec.Decode(&x)
439 dec.tokenState = old
440 if err != nil {
441 return nil, err
442 }
443 dec.tokenState = tokenObjectColon
444 return x, nil
445 }
446 fallthrough
447
448 default:
449 if !dec.tokenValueAllowed() {
450 return dec.tokenError(c)
451 }
452 var x any
453 if err := dec.Decode(&x); err != nil {
454 return nil, err
455 }
456 return x, nil
457 }
458 }
459 }
460
461 func (dec *Decoder) tokenError(c byte) (Token, error) {
462 var context string
463 switch dec.tokenState {
464 case tokenTopValue:
465 context = " looking for beginning of value"
466 case tokenArrayStart, tokenArrayValue, tokenObjectValue:
467 context = " looking for beginning of value"
468 case tokenArrayComma:
469 context = " after array element"
470 case tokenObjectKey:
471 context = " looking for beginning of object key string"
472 case tokenObjectColon:
473 context = " after object key"
474 case tokenObjectComma:
475 context = " after object key:value pair"
476 }
477 return nil, &SyntaxError{"invalid character " + quoteChar(c) + context, dec.InputOffset()}
478 }
479
480
481
482 func (dec *Decoder) More() bool {
483 c, err := dec.peek()
484 return err == nil && c != ']' && c != '}'
485 }
486
487 func (dec *Decoder) peek() (byte, error) {
488 var err error
489 for {
490 for i := dec.scanp; i < len(dec.buf); i++ {
491 c := dec.buf[i]
492 if isSpace(c) {
493 continue
494 }
495 dec.scanp = i
496 return c, nil
497 }
498
499 if err != nil {
500 return 0, err
501 }
502 err = dec.refill()
503 }
504 }
505
506
507
508
509 func (dec *Decoder) InputOffset() int64 {
510 return dec.scanned + int64(dec.scanp)
511 }
512
View as plain text