Debian Codegraph @

internal/golang/encoding/json/stream.go

raw symbols SCIP
1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package json
6
7 import (
8 "bytes"
9 "io"
10 )
11
12 // A Decoder reads and decodes JSON values from an input stream.
13 type Decoder struct {
14 r io.Reader
15 buf []byte
16 d decodeState
17 scanp int // start of unread data in buf
18 scanned int64 // amount of data already scanned
19 scan scanner
20 err error
21
22 tokenState int
23 tokenStack []int
24 }
25
26 // NewDecoder returns a new decoder that reads from r.
27 //
28 // The decoder introduces its own buffering and may
29 // read data from r beyond the JSON values requested.
30 func NewDecoder(r io.Reader) *Decoder {
31 return &Decoder{r: r}
32 }
33
34 // UseNumber causes the Decoder to unmarshal a number into an interface{} as a
35 // [Number] instead of as a float64.
36 func (dec *Decoder) UseNumber() { dec.d.useNumber = true }
37
38 // DisallowUnknownFields causes the Decoder to return an error when the destination
39 // is a struct and the input contains object keys which do not match any
40 // non-ignored, exported fields in the destination.
41 func (dec *Decoder) DisallowUnknownFields() { dec.d.disallowUnknownFields = true }
42
43 // Decode reads the next JSON-encoded value from its
44 // input and stores it in the value pointed to by v.
45 //
46 // See the documentation for [Unmarshal] for details about
47 // the conversion of JSON into a Go value.
48 func (dec *Decoder) Decode(v any) error {
49 if dec.err != nil {
50 return dec.err
51 }
52
53 if err := dec.tokenPrepareForDecode(); err != nil {
54 return err
55 }
56
57 if !dec.tokenValueAllowed() {
58 return &SyntaxError{msg: "not at beginning of value", Offset: dec.InputOffset()}
59 }
60
61 // Read whole value into buffer.
62 n, err := dec.readValue()
63 if err != nil {
64 return err
65 }
66 dec.d.init(dec.buf[dec.scanp : dec.scanp+n])
67 dec.scanp += n
68
69 // Don't save err from unmarshal into dec.err:
70 // the connection is still usable since we read a complete JSON
71 // object from it before the error happened.
72 err = dec.d.unmarshal(v)
73
74 // fixup token streaming state
75 dec.tokenValueEnd()
76
77 return err
78 }
79
80 // Buffered returns a reader of the data remaining in the Decoder's
81 // buffer. The reader is valid until the next call to [Decoder.Decode].
82 func (dec *Decoder) Buffered() io.Reader {
83 return bytes.NewReader(dec.buf[dec.scanp:])
84 }
85
86 // readValue reads a JSON value into dec.buf.
87 // It returns the length of the encoding.
88 func (dec *Decoder) readValue() (int, error) {
89 dec.scan.reset()
90
91 scanp := dec.scanp
92 var err error
93 Input:
94 // help the compiler see that scanp is never negative, so it can remove
95 // some bounds checks below.
96 for scanp >= 0 {
97
98 // Look in the buffer for a new value.
99 for ; scanp < len(dec.buf); scanp++ {
100 c := dec.buf[scanp]
101 dec.scan.bytes++
102 switch dec.scan.step(&dec.scan, c) {
103 case scanEnd:
104 // scanEnd is delayed one byte so we decrement
105 // the scanner bytes count by 1 to ensure that
106 // this value is correct in the next call of Decode.
107 dec.scan.bytes--
108 break Input
109 case scanEndObject, scanEndArray:
110 // scanEnd is delayed one byte.
111 // We might block trying to get that byte from src,
112 // so instead invent a space byte.
113 if stateEndValue(&dec.scan, ' ') == scanEnd {
114 scanp++
115 break Input
116 }
117 case scanError:
118 dec.err = dec.scan.err
119 return 0, dec.scan.err
120 }
121 }
122
123 // Did the last read have an error?
124 // Delayed until now to allow buffer scan.
125 if err != nil {
126 if err == io.EOF {
127 if dec.scan.step(&dec.scan, ' ') == scanEnd {
128 break Input
129 }
130 if nonSpace(dec.buf) {
131 err = io.ErrUnexpectedEOF
132 }
133 }
134 dec.err = err
135 return 0, err
136 }
137
138 n := scanp - dec.scanp
139 err = dec.refill()
140 scanp = dec.scanp + n
141 }
142 return scanp - dec.scanp, nil
143 }
144
145 func (dec *Decoder) refill() error {
146 // Make room to read more into the buffer.
147 // First slide down data already consumed.
148 if dec.scanp > 0 {
149 dec.scanned += int64(dec.scanp)
150 n := copy(dec.buf, dec.buf[dec.scanp:])
151 dec.buf = dec.buf[:n]
152 dec.scanp = 0
153 }
154
155 // Grow buffer if not large enough.
156 const minRead = 512
157 if cap(dec.buf)-len(dec.buf) < minRead {
158 newBuf := make([]byte, len(dec.buf), 2*cap(dec.buf)+minRead)
159 copy(newBuf, dec.buf)
160 dec.buf = newBuf
161 }
162
163 // Read. Delay error for next iteration (after scan).
164 n, err := dec.r.Read(dec.buf[len(dec.buf):cap(dec.buf)])
165 dec.buf = dec.buf[0 : len(dec.buf)+n]
166
167 return err
168 }
169
170 func nonSpace(b []byte) bool {
171 for _, c := range b {
172 if !isSpace(c) {
173 return true
174 }
175 }
176 return false
177 }
178
179 // An Encoder writes JSON values to an output stream.
180 type Encoder struct {
181 w io.Writer
182 err error
183 escapeHTML bool
184
185 indentBuf []byte
186 indentPrefix string
187 indentValue string
188 }
189
190 // NewEncoder returns a new encoder that writes to w.
191 func NewEncoder(w io.Writer) *Encoder {
192 return &Encoder{w: w, escapeHTML: true}
193 }
194
195 // Encode writes the JSON encoding of v to the stream,
196 // with insignificant space characters elided,
197 // followed by a newline character.
198 //
199 // See the documentation for [Marshal] for details about the
200 // conversion of Go values to JSON.
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 // Terminate each value with a newline.
215 // This makes the output look a little nicer
216 // when debugging, and some kind of space
217 // is required if the encoded value was a number,
218 // so that the reader knows there aren't more
219 // digits coming.
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 // SetIndent instructs the encoder to format each subsequent encoded
237 // value as if indented by the package-level function Indent(dst, src, prefix, indent).
238 // Calling SetIndent("", "") disables indentation.
239 func (enc *Encoder) SetIndent(prefix, indent string) {
240 enc.indentPrefix = prefix
241 enc.indentValue = indent
242 }
243
244 // SetEscapeHTML specifies whether problematic HTML characters
245 // should be escaped inside JSON quoted strings.
246 // The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e
247 // to avoid certain safety problems that can arise when embedding JSON in HTML.
248 //
249 // In non-HTML settings where the escaping interferes with the readability
250 // of the output, SetEscapeHTML(false) disables this behavior.
251 func (enc *Encoder) SetEscapeHTML(on bool) {
252 enc.escapeHTML = on
253 }
254
255 /*
256 // RawMessage is a raw encoded JSON value.
257 // It implements [Marshaler] and [Unmarshaler] and can
258 // be used to delay JSON decoding or precompute a JSON encoding.
259 type RawMessage []byte
260
261 // MarshalJSON returns m as the JSON encoding of m.
262 func (m RawMessage) MarshalJSON() ([]byte, error) {
263 if m == nil {
264 return []byte("null"), nil
265 }
266 return m, nil
267 }
268
269 // UnmarshalJSON sets *m to a copy of data.
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
279 var _ Marshaler = (*RawMessage)(nil)
280 var _ Unmarshaler = (*RawMessage)(nil)
281
282 /*
283 // A Token holds a value of one of these types:
284 //
285 // - [Delim], for the four JSON delimiters [ ] { }
286 // - bool, for JSON booleans
287 // - float64, for JSON numbers
288 // - [Number], for JSON numbers
289 // - string, for JSON string literals
290 // - nil, for JSON null
291 type Token any
292 */
293
294 const (
295 tokenTopValue = iota
296 tokenArrayStart
297 tokenArrayValue
298 tokenArrayComma
299 tokenObjectStart
300 tokenObjectKey
301 tokenObjectColon
302 tokenObjectValue
303 tokenObjectComma
304 )
305
306 // advance tokenstate from a separator state to a value state
307 func (dec *Decoder) tokenPrepareForDecode() error {
308 // Note: Not calling peek before switch, to avoid
309 // putting peek into the standard Decode path.
310 // peek is only called when using the Token API.
311 switch dec.tokenState {
312 case tokenArrayComma:
313 c, err := dec.peek()
314 if err != nil {
315 return err
316 }
317 if c != ',' {
318 return &SyntaxError{"expected comma after array element", dec.InputOffset()}
319 }
320 dec.scanp++
321 dec.tokenState = tokenArrayValue
322 case tokenObjectColon:
323 c, err := dec.peek()
324 if err != nil {
325 return err
326 }
327 if c != ':' {
328 return &SyntaxError{"expected colon after object key", dec.InputOffset()}
329 }
330 dec.scanp++
331 dec.tokenState = tokenObjectValue
332 }
333 return nil
334 }
335
336 func (dec *Decoder) tokenValueAllowed() bool {
337 switch dec.tokenState {
338 case tokenTopValue, tokenArrayStart, tokenArrayValue, tokenObjectValue:
339 return true
340 }
341 return false
342 }
343
344 func (dec *Decoder) tokenValueEnd() {
345 switch dec.tokenState {
346 case tokenArrayStart, tokenArrayValue:
347 dec.tokenState = tokenArrayComma
348 case tokenObjectValue:
349 dec.tokenState = tokenObjectComma
350 }
351 }
352
353 /*
354 // A Delim is a JSON array or object delimiter, one of [ ] { or }.
355 type Delim rune
356
357 func (d Delim) String() string {
358 return string(d)
359 }
360 */
361
362 // Token returns the next JSON token in the input stream.
363 // At the end of the input stream, Token returns nil, [io.EOF].
364 //
365 // Token guarantees that the delimiters [ ] { } it returns are
366 // properly nested and matched: if Token encounters an unexpected
367 // delimiter in the input, it will return an error.
368 //
369 // The input stream consists of basic JSON values—bool, string,
370 // number, and null—along with delimiters [ ] { } of type [Delim]
371 // to mark the start and end of arrays and objects.
372 // Commas and colons are elided.
373 func (dec *Decoder) Token() (Token, error) {
374 for {
375 c, err := dec.peek()
376 if err != nil {
377 return nil, err
378 }
379 switch c {
380 case '[':
381 if !dec.tokenValueAllowed() {
382 return dec.tokenError(c)
383 }
384 dec.scanp++
385 dec.tokenStack = append(dec.tokenStack, dec.tokenState)
386 dec.tokenState = tokenArrayStart
387 return Delim('['), nil
388
389 case ']':
390 if dec.tokenState != tokenArrayStart && dec.tokenState != tokenArrayComma {
391 return dec.tokenError(c)
392 }
393 dec.scanp++
394 dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1]
395 dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1]
396 dec.tokenValueEnd()
397 return Delim(']'), nil
398
399 case '{':
400 if !dec.tokenValueAllowed() {
401 return dec.tokenError(c)
402 }
403 dec.scanp++
404 dec.tokenStack = append(dec.tokenStack, dec.tokenState)
405 dec.tokenState = tokenObjectStart
406 return Delim('{'), nil
407
408 case '}':
409 if dec.tokenState != tokenObjectStart && dec.tokenState != tokenObjectComma {
410 return dec.tokenError(c)
411 }
412 dec.scanp++
413 dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1]
414 dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1]
415 dec.tokenValueEnd()
416 return Delim('}'), nil
417
418 case ':':
419 if dec.tokenState != tokenObjectColon {
420 return dec.tokenError(c)
421 }
422 dec.scanp++
423 dec.tokenState = tokenObjectValue
424 continue
425
426 case ',':
427 if dec.tokenState == tokenArrayComma {
428 dec.scanp++
429 dec.tokenState = tokenArrayValue
430 continue
431 }
432 if dec.tokenState == tokenObjectComma {
433 dec.scanp++
434 dec.tokenState = tokenObjectKey
435 continue
436 }
437 return dec.tokenError(c)
438
439 case '"':
440 if dec.tokenState == tokenObjectStart || dec.tokenState == tokenObjectKey {
441 var x string
442 old := dec.tokenState
443 dec.tokenState = tokenTopValue
444 err := dec.Decode(&x)
445 dec.tokenState = old
446 if err != nil {
447 return nil, err
448 }
449 dec.tokenState = tokenObjectColon
450 return x, nil
451 }
452 fallthrough
453
454 default:
455 if !dec.tokenValueAllowed() {
456 return dec.tokenError(c)
457 }
458 var x any
459 if err := dec.Decode(&x); err != nil {
460 return nil, err
461 }
462 return x, nil
463 }
464 }
465 }
466
467 func (dec *Decoder) tokenError(c byte) (Token, error) {
468 var context string
469 switch dec.tokenState {
470 case tokenTopValue:
471 context = " looking for beginning of value"
472 case tokenArrayStart, tokenArrayValue, tokenObjectValue:
473 context = " looking for beginning of value"
474 case tokenArrayComma:
475 context = " after array element"
476 case tokenObjectKey:
477 context = " looking for beginning of object key string"
478 case tokenObjectColon:
479 context = " after object key"
480 case tokenObjectComma:
481 context = " after object key:value pair"
482 }
483 return nil, &SyntaxError{"invalid character " + quoteChar(c) + context, dec.InputOffset()}
484 }
485
486 // More reports whether there is another element in the
487 // current array or object being parsed.
488 func (dec *Decoder) More() bool {
489 c, err := dec.peek()
490 return err == nil && c != ']' && c != '}'
491 }
492
493 func (dec *Decoder) peek() (byte, error) {
494 var err error
495 for {
496 for i := dec.scanp; i < len(dec.buf); i++ {
497 c := dec.buf[i]
498 if isSpace(c) {
499 continue
500 }
501 dec.scanp = i
502 return c, nil
503 }
504 // buffer has been scanned, now report any error
505 if err != nil {
506 return 0, err
507 }
508 err = dec.refill()
509 }
510 }
511
512 // InputOffset returns the input stream byte offset of the current decoder position.
513 // The offset gives the location of the end of the most recently returned token
514 // and the beginning of the next token.
515 func (dec *Decoder) InputOffset() int64 {
516 return dec.scanned + int64(dec.scanp)
517 }