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
202 func (enc *Encoder) Encode(v any) error {
203 if enc.err != nil {
204 return enc.err
205 }
206
207 e := newEncodeState()
208 defer encodeStatePool.Put(e)
209
210 err := e.marshal(v, encOpts{escapeHTML: enc.escapeHTML})
211 if err != nil {
212 return err
213 }
214
215
216
217
218
219
220
221 e.WriteByte('\n')
222
223 b := e.Bytes()
224 if enc.indentPrefix != "" || enc.indentValue != "" {
225 enc.indentBuf, err = appendIndent(enc.indentBuf[:0], b, enc.indentPrefix, enc.indentValue)
226 if err != nil {
227 return err
228 }
229 b = enc.indentBuf
230 }
231 if _, err = enc.w.Write(b); err != nil {
232 enc.err = err
233 }
234 return err
235 }
236
237
238
239
240 func (enc *Encoder) SetIndent(prefix, indent string) {
241 enc.indentPrefix = prefix
242 enc.indentValue = indent
243 }
244
245
246
247
248
249
250
251
252 func (enc *Encoder) SetEscapeHTML(on bool) {
253 enc.escapeHTML = on
254 }
255
256
257
258
259 type RawMessage []byte
260
261
262 func (m RawMessage) MarshalJSON() ([]byte, error) {
263 if m == nil {
264 return []byte("null"), nil
265 }
266 return m, nil
267 }
268
269
270 func (m *RawMessage) UnmarshalJSON(data []byte) error {
271 if m == nil {
272 return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
273 }
274 *m = append((*m)[0:0], data...)
275 return nil
276 }
277
278 var _ Marshaler = (*RawMessage)(nil)
279 var _ Unmarshaler = (*RawMessage)(nil)
280
281
282
283
284
285
286
287
288
289 type Token any
290
291 const (
292 tokenTopValue = iota
293 tokenArrayStart
294 tokenArrayValue
295 tokenArrayComma
296 tokenObjectStart
297 tokenObjectKey
298 tokenObjectColon
299 tokenObjectValue
300 tokenObjectComma
301 )
302
303
304 func (dec *Decoder) tokenPrepareForDecode() error {
305
306
307
308 switch dec.tokenState {
309 case tokenArrayComma:
310 c, err := dec.peek()
311 if err != nil {
312 return err
313 }
314 if c != ',' {
315 return &SyntaxError{"expected comma after array element", dec.InputOffset()}
316 }
317 dec.scanp++
318 dec.tokenState = tokenArrayValue
319 case tokenObjectColon:
320 c, err := dec.peek()
321 if err != nil {
322 return err
323 }
324 if c != ':' {
325 return &SyntaxError{"expected colon after object key", dec.InputOffset()}
326 }
327 dec.scanp++
328 dec.tokenState = tokenObjectValue
329 }
330 return nil
331 }
332
333 func (dec *Decoder) tokenValueAllowed() bool {
334 switch dec.tokenState {
335 case tokenTopValue, tokenArrayStart, tokenArrayValue, tokenObjectValue:
336 return true
337 }
338 return false
339 }
340
341 func (dec *Decoder) tokenValueEnd() {
342 switch dec.tokenState {
343 case tokenArrayStart, tokenArrayValue:
344 dec.tokenState = tokenArrayComma
345 case tokenObjectValue:
346 dec.tokenState = tokenObjectComma
347 }
348 }
349
350
351 type Delim rune
352
353 func (d Delim) String() string {
354 return string(d)
355 }
356
357
358
359
360
361
362
363
364
365
366
367
368 func (dec *Decoder) Token() (Token, error) {
369 for {
370 c, err := dec.peek()
371 if err != nil {
372 return nil, err
373 }
374 switch c {
375 case '[':
376 if !dec.tokenValueAllowed() {
377 return dec.tokenError(c)
378 }
379 dec.scanp++
380 dec.tokenStack = append(dec.tokenStack, dec.tokenState)
381 dec.tokenState = tokenArrayStart
382 return Delim('['), nil
383
384 case ']':
385 if dec.tokenState != tokenArrayStart && dec.tokenState != tokenArrayComma {
386 return dec.tokenError(c)
387 }
388 dec.scanp++
389 dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1]
390 dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1]
391 dec.tokenValueEnd()
392 return Delim(']'), nil
393
394 case '{':
395 if !dec.tokenValueAllowed() {
396 return dec.tokenError(c)
397 }
398 dec.scanp++
399 dec.tokenStack = append(dec.tokenStack, dec.tokenState)
400 dec.tokenState = tokenObjectStart
401 return Delim('{'), nil
402
403 case '}':
404 if dec.tokenState != tokenObjectStart && dec.tokenState != tokenObjectComma {
405 return dec.tokenError(c)
406 }
407 dec.scanp++
408 dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1]
409 dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1]
410 dec.tokenValueEnd()
411 return Delim('}'), nil
412
413 case ':':
414 if dec.tokenState != tokenObjectColon {
415 return dec.tokenError(c)
416 }
417 dec.scanp++
418 dec.tokenState = tokenObjectValue
419 continue
420
421 case ',':
422 if dec.tokenState == tokenArrayComma {
423 dec.scanp++
424 dec.tokenState = tokenArrayValue
425 continue
426 }
427 if dec.tokenState == tokenObjectComma {
428 dec.scanp++
429 dec.tokenState = tokenObjectKey
430 continue
431 }
432 return dec.tokenError(c)
433
434 case '"':
435 if dec.tokenState == tokenObjectStart || dec.tokenState == tokenObjectKey {
436 var x string
437 old := dec.tokenState
438 dec.tokenState = tokenTopValue
439 err := dec.Decode(&x)
440 dec.tokenState = old
441 if err != nil {
442 return nil, err
443 }
444 dec.tokenState = tokenObjectColon
445 return x, nil
446 }
447 fallthrough
448
449 default:
450 if !dec.tokenValueAllowed() {
451 return dec.tokenError(c)
452 }
453 var x any
454 if err := dec.Decode(&x); err != nil {
455 return nil, err
456 }
457 return x, nil
458 }
459 }
460 }
461
462 func (dec *Decoder) tokenError(c byte) (Token, error) {
463 var context string
464 switch dec.tokenState {
465 case tokenTopValue:
466 context = " looking for beginning of value"
467 case tokenArrayStart, tokenArrayValue, tokenObjectValue:
468 context = " looking for beginning of value"
469 case tokenArrayComma:
470 context = " after array element"
471 case tokenObjectKey:
472 context = " looking for beginning of object key string"
473 case tokenObjectColon:
474 context = " after object key"
475 case tokenObjectComma:
476 context = " after object key:value pair"
477 }
478 return nil, &SyntaxError{"invalid character " + quoteChar(c) + context, dec.InputOffset()}
479 }
480
481
482
483 func (dec *Decoder) More() bool {
484 c, err := dec.peek()
485 return err == nil && c != ']' && c != '}'
486 }
487
488 func (dec *Decoder) peek() (byte, error) {
489 var err error
490 for {
491 for i := dec.scanp; i < len(dec.buf); i++ {
492 c := dec.buf[i]
493 if isSpace(c) {
494 continue
495 }
496 dec.scanp = i
497 return c, nil
498 }
499
500 if err != nil {
501 return 0, err
502 }
503 err = dec.refill()
504 }
505 }
506
507
508
509
510 func (dec *Decoder) InputOffset() int64 {
511 return dec.scanned + int64(dec.scanp)
512 }
513
View as plain text