| 1 |
// Copyright 2020 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 |
//go:build goexperiment.jsonv2 |
| 6 |
|
| 7 |
package jsontext |
| 8 |
|
| 9 |
import ( |
| 10 |
"bytes" |
| 11 |
"errors" |
| 12 |
"io" |
| 13 |
|
| 14 |
"encoding/json/internal/jsonflags" |
| 15 |
"encoding/json/internal/jsonopts" |
| 16 |
"encoding/json/internal/jsonwire" |
| 17 |
) |
| 18 |
|
| 19 |
// NOTE: The logic for decoding is complicated by the fact that reading from |
| 20 |
// an io.Reader into a temporary buffer means that the buffer may contain a |
| 21 |
// truncated portion of some valid input, requiring the need to fetch more data. |
| 22 |
// |
| 23 |
// This file is structured in the following way: |
| 24 |
// |
| 25 |
// - consumeXXX functions parse an exact JSON token from a []byte. |
| 26 |
// If the buffer appears truncated, then it returns io.ErrUnexpectedEOF. |
| 27 |
// The consumeSimpleXXX functions are so named because they only handle |
| 28 |
// a subset of the grammar for the JSON token being parsed. |
| 29 |
// They do not handle the full grammar to keep these functions inlinable. |
| 30 |
// |
| 31 |
// - Decoder.consumeXXX methods parse the next JSON token from Decoder.buf, |
| 32 |
// automatically fetching more input if necessary. These methods take |
| 33 |
// a position relative to the start of Decoder.buf as an argument and |
| 34 |
// return the end of the consumed JSON token as a position, |
| 35 |
// also relative to the start of Decoder.buf. |
| 36 |
// |
| 37 |
// - In the event of an I/O errors or state machine violations, |
| 38 |
// the implementation avoids mutating the state of Decoder |
| 39 |
// (aside from the book-keeping needed to implement Decoder.fetch). |
| 40 |
// For this reason, only Decoder.ReadToken and Decoder.ReadValue are |
| 41 |
// responsible for updated Decoder.prevStart and Decoder.prevEnd. |
| 42 |
// |
| 43 |
// - For performance, much of the implementation uses the pattern of calling |
| 44 |
// the inlinable consumeXXX functions first, and if more work is necessary, |
| 45 |
// then it calls the slower Decoder.consumeXXX methods. |
| 46 |
// TODO: Revisit this pattern if the Go compiler provides finer control |
| 47 |
// over exactly which calls are inlined or not. |
| 48 |
|
| 49 |
// Decoder is a streaming decoder for raw JSON tokens and values. |
| 50 |
// It is used to read a stream of top-level JSON values, |
| 51 |
// each separated by optional whitespace characters. |
| 52 |
// |
| 53 |
// [Decoder.ReadToken] and [Decoder.ReadValue] calls may be interleaved. |
| 54 |
// For example, the following JSON value: |
| 55 |
// |
| 56 |
// {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}} |
| 57 |
// |
| 58 |
// can be parsed with the following calls (ignoring errors for brevity): |
| 59 |
// |
| 60 |
// d.ReadToken() // { |
| 61 |
// d.ReadToken() // "name" |
| 62 |
// d.ReadToken() // "value" |
| 63 |
// d.ReadValue() // "array" |
| 64 |
// d.ReadToken() // [ |
| 65 |
// d.ReadToken() // null |
| 66 |
// d.ReadToken() // false |
| 67 |
// d.ReadValue() // true |
| 68 |
// d.ReadToken() // 3.14159 |
| 69 |
// d.ReadToken() // ] |
| 70 |
// d.ReadValue() // "object" |
| 71 |
// d.ReadValue() // {"k":"v"} |
| 72 |
// d.ReadToken() // } |
| 73 |
// |
| 74 |
// The above is one of many possible sequence of calls and |
| 75 |
// may not represent the most sensible method to call for any given token/value. |
| 76 |
// For example, it is probably more common to call [Decoder.ReadToken] to obtain a |
| 77 |
// string token for object names. |
| 78 |
type Decoder struct { |
| 79 |
s decoderState |
| 80 |
} |
| 81 |
|
| 82 |
// decoderState is the low-level state of Decoder. |
| 83 |
// It has exported fields and method for use by the "json" package. |
| 84 |
type decoderState struct { |
| 85 |
state |
| 86 |
decodeBuffer |
| 87 |
jsonopts.Struct |
| 88 |
|
| 89 |
StringCache *[256]string // only used when unmarshaling; identical to json.stringCache |
| 90 |
} |
| 91 |
|
| 92 |
// decodeBuffer is a buffer split into 4 segments: |
| 93 |
// |
| 94 |
// - buf[0:prevEnd] // already read portion of the buffer |
| 95 |
// - buf[prevStart:prevEnd] // previously read value |
| 96 |
// - buf[prevEnd:len(buf)] // unread portion of the buffer |
| 97 |
// - buf[len(buf):cap(buf)] // unused portion of the buffer |
| 98 |
// |
| 99 |
// Invariants: |
| 100 |
// |
| 101 |
// 0 ≤ prevStart ≤ prevEnd ≤ len(buf) ≤ cap(buf) |
| 102 |
type decodeBuffer struct { |
| 103 |
peekPos int // non-zero if valid offset into buf for start of next token |
| 104 |
peekErr error // implies peekPos is -1 |
| 105 |
|
| 106 |
buf []byte // may alias rd if it is a bytes.Buffer |
| 107 |
prevStart int |
| 108 |
prevEnd int |
| 109 |
|
| 110 |
// baseOffset is added to prevStart and prevEnd to obtain |
| 111 |
// the absolute offset relative to the start of io.Reader stream. |
| 112 |
baseOffset int64 |
| 113 |
|
| 114 |
rd io.Reader |
| 115 |
} |
| 116 |
|
| 117 |
// NewDecoder constructs a new streaming decoder reading from r. |
| 118 |
// |
| 119 |
// If r is a [bytes.Buffer], then the decoder parses directly from the buffer |
| 120 |
// without first copying the contents to an intermediate buffer. |
| 121 |
// Additional writes to the buffer must not occur while the decoder is in use. |
| 122 |
func NewDecoder(r io.Reader, opts ...Options) *Decoder { |
| 123 |
d := new(Decoder) |
| 124 |
d.Reset(r, opts...) |
| 125 |
return d |
| 126 |
} |
| 127 |
|
| 128 |
// Reset resets a decoder such that it is reading afresh from r and |
| 129 |
// configured with the provided options. Reset must not be called on an |
| 130 |
// a Decoder passed to the [encoding/json/v2.UnmarshalerFrom.UnmarshalJSONFrom] method |
| 131 |
// or the [encoding/json/v2.UnmarshalFromFunc] function. |
| 132 |
func (d *Decoder) Reset(r io.Reader, opts ...Options) { |
| 133 |
switch { |
| 134 |
case d == nil: |
| 135 |
panic("jsontext: invalid nil Decoder") |
| 136 |
case r == nil: |
| 137 |
panic("jsontext: invalid nil io.Reader") |
| 138 |
case d.s.Flags.Get(jsonflags.WithinArshalCall): |
| 139 |
panic("jsontext: cannot reset Decoder passed to json.UnmarshalerFrom") |
| 140 |
} |
| 141 |
// Reuse the buffer if it does not alias a previous [bytes.Buffer]. |
| 142 |
b := d.s.buf[:0] |
| 143 |
if _, ok := d.s.rd.(*bytes.Buffer); ok { |
| 144 |
b = nil |
| 145 |
} |
| 146 |
d.s.reset(b, r, opts...) |
| 147 |
} |
| 148 |
|
| 149 |
func (d *decoderState) reset(b []byte, r io.Reader, opts ...Options) { |
| 150 |
d.state.reset() |
| 151 |
d.decodeBuffer = decodeBuffer{buf: b, rd: r} |
| 152 |
opts2 := jsonopts.Struct{} // avoid mutating d.Struct in case it is part of opts |
| 153 |
opts2.Join(opts...) |
| 154 |
d.Struct = opts2 |
| 155 |
} |
| 156 |
|
| 157 |
// Options returns the options used to construct the encoder and |
| 158 |
// may additionally contain semantic options passed to a |
| 159 |
// [encoding/json/v2.UnmarshalDecode] call. |
| 160 |
// |
| 161 |
// If operating within |
| 162 |
// a [encoding/json/v2.UnmarshalerFrom.UnmarshalJSONFrom] method call or |
| 163 |
// a [encoding/json/v2.UnmarshalFromFunc] function call, |
| 164 |
// then the returned options are only valid within the call. |
| 165 |
func (d *Decoder) Options() Options { |
| 166 |
return &d.s.Struct |
| 167 |
} |
| 168 |
|
| 169 |
var errBufferWriteAfterNext = errors.New("invalid bytes.Buffer.Write call after calling bytes.Buffer.Next") |
| 170 |
|
| 171 |
// fetch reads at least 1 byte from the underlying io.Reader. |
| 172 |
// It returns io.ErrUnexpectedEOF if zero bytes were read and io.EOF was seen. |
| 173 |
func (d *decoderState) fetch() error { |
| 174 |
if d.rd == nil { |
| 175 |
return io.ErrUnexpectedEOF |
| 176 |
} |
| 177 |
|
| 178 |
// Inform objectNameStack that we are about to fetch new buffer content. |
| 179 |
d.Names.copyQuotedBuffer(d.buf) |
| 180 |
|
| 181 |
// Specialize bytes.Buffer for better performance. |
| 182 |
if bb, ok := d.rd.(*bytes.Buffer); ok { |
| 183 |
switch { |
| 184 |
case bb.Len() == 0: |
| 185 |
return io.ErrUnexpectedEOF |
| 186 |
case len(d.buf) == 0: |
| 187 |
d.buf = bb.Next(bb.Len()) // "read" all data in the buffer |
| 188 |
return nil |
| 189 |
default: |
| 190 |
// This only occurs if a partially filled bytes.Buffer was provided |
| 191 |
// and more data is written to it while Decoder is reading from it. |
| 192 |
// This practice will lead to data corruption since future writes |
| 193 |
// may overwrite the contents of the current buffer. |
| 194 |
// |
| 195 |
// The user is trying to use a bytes.Buffer as a pipe, |
| 196 |
// but a bytes.Buffer is poor implementation of a pipe, |
| 197 |
// the purpose-built io.Pipe should be used instead. |
| 198 |
return &ioError{action: "read", err: errBufferWriteAfterNext} |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
// Allocate initial buffer if empty. |
| 203 |
if cap(d.buf) == 0 { |
| 204 |
d.buf = make([]byte, 0, 64) |
| 205 |
} |
| 206 |
|
| 207 |
// Check whether to grow the buffer. |
| 208 |
const maxBufferSize = 4 << 10 |
| 209 |
const growthSizeFactor = 2 // higher value is faster |
| 210 |
const growthRateFactor = 2 // higher value is slower |
| 211 |
// By default, grow if below the maximum buffer size. |
| 212 |
grow := cap(d.buf) <= maxBufferSize/growthSizeFactor |
| 213 |
// Growing can be expensive, so only grow |
| 214 |
// if a sufficient number of bytes have been processed. |
| 215 |
grow = grow && int64(cap(d.buf)) < d.previousOffsetEnd()/growthRateFactor |
| 216 |
// If prevStart==0, then fetch was called in order to fetch more data |
| 217 |
// to finish consuming a large JSON value contiguously. |
| 218 |
// Grow if less than 25% of the remaining capacity is available. |
| 219 |
// Note that this may cause the input buffer to exceed maxBufferSize. |
| 220 |
grow = grow || (d.prevStart == 0 && len(d.buf) >= 3*cap(d.buf)/4) |
| 221 |
|
| 222 |
if grow { |
| 223 |
// Allocate a new buffer and copy the contents of the old buffer over. |
| 224 |
// TODO: Provide a hard limit on the maximum internal buffer size? |
| 225 |
buf := make([]byte, 0, cap(d.buf)*growthSizeFactor) |
| 226 |
d.buf = append(buf, d.buf[d.prevStart:]...) |
| 227 |
} else { |
| 228 |
// Move unread portion of the data to the front. |
| 229 |
n := copy(d.buf[:cap(d.buf)], d.buf[d.prevStart:]) |
| 230 |
d.buf = d.buf[:n] |
| 231 |
} |
| 232 |
d.baseOffset += int64(d.prevStart) |
| 233 |
d.prevEnd -= d.prevStart |
| 234 |
d.prevStart = 0 |
| 235 |
|
| 236 |
// Read more data into the internal buffer. |
| 237 |
for { |
| 238 |
n, err := d.rd.Read(d.buf[len(d.buf):cap(d.buf)]) |
| 239 |
switch { |
| 240 |
case n > 0: |
| 241 |
d.buf = d.buf[:len(d.buf)+n] |
| 242 |
return nil // ignore errors if any bytes are read |
| 243 |
case err == io.EOF: |
| 244 |
return io.ErrUnexpectedEOF |
| 245 |
case err != nil: |
| 246 |
return &ioError{action: "read", err: err} |
| 247 |
default: |
| 248 |
continue // Read returned (0, nil) |
| 249 |
} |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
const invalidateBufferByte = '#' // invalid starting character for JSON grammar |
| 254 |
|
| 255 |
// invalidatePreviousRead invalidates buffers returned by Peek and Read calls |
| 256 |
// so that the first byte is an invalid character. |
| 257 |
// This Hyrum-proofs the API against faulty application code that assumes |
| 258 |
// values returned by ReadValue remain valid past subsequent Read calls. |
| 259 |
func (d *decodeBuffer) invalidatePreviousRead() { |
| 260 |
// Avoid mutating the buffer if d.rd is nil which implies that d.buf |
| 261 |
// is provided by the user code and may not expect mutations. |
| 262 |
isBytesBuffer := func(r io.Reader) bool { |
| 263 |
_, ok := r.(*bytes.Buffer) |
| 264 |
return ok |
| 265 |
} |
| 266 |
if d.rd != nil && !isBytesBuffer(d.rd) && d.prevStart < d.prevEnd && uint(d.prevStart) < uint(len(d.buf)) { |
| 267 |
d.buf[d.prevStart] = invalidateBufferByte |
| 268 |
d.prevStart = d.prevEnd |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
// needMore reports whether there are no more unread bytes. |
| 273 |
func (d *decodeBuffer) needMore(pos int) bool { |
| 274 |
// NOTE: The arguments and logic are kept simple to keep this inlinable. |
| 275 |
return pos == len(d.buf) |
| 276 |
} |
| 277 |
|
| 278 |
func (d *decodeBuffer) offsetAt(pos int) int64 { return d.baseOffset + int64(pos) } |
| 279 |
func (d *decodeBuffer) previousOffsetStart() int64 { return d.baseOffset + int64(d.prevStart) } |
| 280 |
func (d *decodeBuffer) previousOffsetEnd() int64 { return d.baseOffset + int64(d.prevEnd) } |
| 281 |
func (d *decodeBuffer) previousBuffer() []byte { return d.buf[d.prevStart:d.prevEnd] } |
| 282 |
func (d *decodeBuffer) unreadBuffer() []byte { return d.buf[d.prevEnd:len(d.buf)] } |
| 283 |
|
| 284 |
// PreviousTokenOrValue returns the previously read token or value |
| 285 |
// unless it has been invalidated by a call to PeekKind. |
| 286 |
// If a token is just a delimiter, then this returns a 1-byte buffer. |
| 287 |
// This method is used for error reporting at the semantic layer. |
| 288 |
func (d *decodeBuffer) PreviousTokenOrValue() []byte { |
| 289 |
b := d.previousBuffer() |
| 290 |
// If peek was called, then the previous token or buffer is invalidated. |
| 291 |
if d.peekPos > 0 || len(b) > 0 && b[0] == invalidateBufferByte { |
| 292 |
return nil |
| 293 |
} |
| 294 |
// ReadToken does not preserve the buffer for null, bools, or delimiters. |
| 295 |
// Manually re-construct that buffer. |
| 296 |
if len(b) == 0 { |
| 297 |
b = d.buf[:d.prevEnd] // entirety of the previous buffer |
| 298 |
for _, tok := range []string{"null", "false", "true", "{", "}", "[", "]"} { |
| 299 |
if len(b) >= len(tok) && string(b[len(b)-len(tok):]) == tok { |
| 300 |
return b[len(b)-len(tok):] |
| 301 |
} |
| 302 |
} |
| 303 |
} |
| 304 |
return b |
| 305 |
} |
| 306 |
|
| 307 |
// PeekKind retrieves the next token kind, but does not advance the read offset. |
| 308 |
// |
| 309 |
// It returns [KindInvalid] if an error occurs. Any such error is cached until |
| 310 |
// the next read call and it is the caller's responsibility to eventually |
| 311 |
// follow up a PeekKind call with a read call. |
| 312 |
func (d *Decoder) PeekKind() Kind { |
| 313 |
return d.s.PeekKind() |
| 314 |
} |
| 315 |
func (d *decoderState) PeekKind() Kind { |
| 316 |
// Check whether we have a cached peek result. |
| 317 |
if d.peekPos > 0 { |
| 318 |
return Kind(d.buf[d.peekPos]).normalize() |
| 319 |
} |
| 320 |
|
| 321 |
var err error |
| 322 |
d.invalidatePreviousRead() |
| 323 |
pos := d.prevEnd |
| 324 |
|
| 325 |
// Consume leading whitespace. |
| 326 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 327 |
if d.needMore(pos) { |
| 328 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 329 |
if err == io.ErrUnexpectedEOF && d.Tokens.Depth() == 1 { |
| 330 |
err = io.EOF // EOF possibly if no Tokens present after top-level value |
| 331 |
} |
| 332 |
d.peekPos, d.peekErr = -1, wrapSyntacticError(d, err, pos, 0) |
| 333 |
return invalidKind |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
// Consume colon or comma. |
| 338 |
var delim byte |
| 339 |
if c := d.buf[pos]; c == ':' || c == ',' { |
| 340 |
delim = c |
| 341 |
pos += 1 |
| 342 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 343 |
if d.needMore(pos) { |
| 344 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 345 |
err = wrapSyntacticError(d, err, pos, 0) |
| 346 |
d.peekPos, d.peekErr = -1, d.checkDelimBeforeIOError(delim, err) |
| 347 |
return invalidKind |
| 348 |
} |
| 349 |
} |
| 350 |
} |
| 351 |
next := Kind(d.buf[pos]).normalize() |
| 352 |
if d.Tokens.needDelim(next) != delim { |
| 353 |
d.peekPos, d.peekErr = -1, d.checkDelim(delim, next) |
| 354 |
return invalidKind |
| 355 |
} |
| 356 |
|
| 357 |
// This may set peekPos to zero, which is indistinguishable from |
| 358 |
// the uninitialized state. While a small hit to performance, it is correct |
| 359 |
// since ReadValue and ReadToken will disregard the cached result and |
| 360 |
// recompute the next kind. |
| 361 |
d.peekPos, d.peekErr = pos, nil |
| 362 |
return next |
| 363 |
} |
| 364 |
|
| 365 |
// checkDelimBeforeIOError checks whether the delim is even valid |
| 366 |
// before returning an IO error, which occurs after the delim. |
| 367 |
func (d *decoderState) checkDelimBeforeIOError(delim byte, err error) error { |
| 368 |
// Since an IO error occurred, we do not know what the next kind is. |
| 369 |
// However, knowing the next kind is necessary to validate |
| 370 |
// whether the current delim is at least potentially valid. |
| 371 |
// Since a JSON string is always valid as the next token, |
| 372 |
// conservatively assume that is the next kind for validation. |
| 373 |
const next = Kind('"') |
| 374 |
if d.Tokens.needDelim(next) != delim { |
| 375 |
err = d.checkDelim(delim, next) |
| 376 |
} |
| 377 |
return err |
| 378 |
} |
| 379 |
|
| 380 |
// CountNextDelimWhitespace counts the number of upcoming bytes of |
| 381 |
// delimiter or whitespace characters. |
| 382 |
// This method is used for error reporting at the semantic layer. |
| 383 |
func (d *decoderState) CountNextDelimWhitespace() int { |
| 384 |
d.PeekKind() // populate unreadBuffer |
| 385 |
return len(d.unreadBuffer()) - len(bytes.TrimLeft(d.unreadBuffer(), ",: \n\r\t")) |
| 386 |
} |
| 387 |
|
| 388 |
// checkDelim checks whether delim is valid for the given next kind. |
| 389 |
func (d *decoderState) checkDelim(delim byte, next Kind) error { |
| 390 |
where := "at start of value" |
| 391 |
switch d.Tokens.needDelim(next) { |
| 392 |
case delim: |
| 393 |
return nil |
| 394 |
case ':': |
| 395 |
where = "after object name (expecting ':')" |
| 396 |
case ',': |
| 397 |
if d.Tokens.Last.isObject() { |
| 398 |
where = "after object value (expecting ',' or '}')" |
| 399 |
} else { |
| 400 |
where = "after array element (expecting ',' or ']')" |
| 401 |
} |
| 402 |
} |
| 403 |
pos := d.prevEnd // restore position to right after leading whitespace |
| 404 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 405 |
err := jsonwire.NewInvalidCharacterError(d.buf[pos:], where) |
| 406 |
return wrapSyntacticError(d, err, pos, 0) |
| 407 |
} |
| 408 |
|
| 409 |
// SkipValue is semantically equivalent to calling [Decoder.ReadValue] and discarding |
| 410 |
// the result except that memory is not wasted trying to hold the entire result. |
| 411 |
func (d *Decoder) SkipValue() error { |
| 412 |
return d.s.SkipValue() |
| 413 |
} |
| 414 |
func (d *decoderState) SkipValue() error { |
| 415 |
switch d.PeekKind() { |
| 416 |
case '{', '[': |
| 417 |
// For JSON objects and arrays, keep skipping all tokens |
| 418 |
// until the depth matches the starting depth. |
| 419 |
depth := d.Tokens.Depth() |
| 420 |
for { |
| 421 |
if _, err := d.ReadToken(); err != nil { |
| 422 |
return err |
| 423 |
} |
| 424 |
if depth >= d.Tokens.Depth() { |
| 425 |
return nil |
| 426 |
} |
| 427 |
} |
| 428 |
default: |
| 429 |
// Trying to skip a value when the next token is a '}' or ']' |
| 430 |
// will result in an error being returned here. |
| 431 |
var flags jsonwire.ValueFlags |
| 432 |
if _, err := d.ReadValue(&flags); err != nil { |
| 433 |
return err |
| 434 |
} |
| 435 |
return nil |
| 436 |
} |
| 437 |
} |
| 438 |
|
| 439 |
// SkipValueRemainder skips the remainder of a value |
| 440 |
// after reading a '{' or '[' token. |
| 441 |
func (d *decoderState) SkipValueRemainder() error { |
| 442 |
if d.Tokens.Depth()-1 > 0 && d.Tokens.Last.Length() == 0 { |
| 443 |
for n := d.Tokens.Depth(); d.Tokens.Depth() >= n; { |
| 444 |
if _, err := d.ReadToken(); err != nil { |
| 445 |
return err |
| 446 |
} |
| 447 |
} |
| 448 |
} |
| 449 |
return nil |
| 450 |
} |
| 451 |
|
| 452 |
// SkipUntil skips all tokens until the state machine |
| 453 |
// is at or past the specified depth and length. |
| 454 |
func (d *decoderState) SkipUntil(depth int, length int64) error { |
| 455 |
for d.Tokens.Depth() > depth || (d.Tokens.Depth() == depth && d.Tokens.Last.Length() < length) { |
| 456 |
if _, err := d.ReadToken(); err != nil { |
| 457 |
return err |
| 458 |
} |
| 459 |
} |
| 460 |
return nil |
| 461 |
} |
| 462 |
|
| 463 |
// ReadToken reads the next [Token], advancing the read offset. |
| 464 |
// The returned token is only valid until the next Peek, Read, or Skip call. |
| 465 |
// It returns [io.EOF] if there are no more tokens. |
| 466 |
func (d *Decoder) ReadToken() (Token, error) { |
| 467 |
return d.s.ReadToken() |
| 468 |
} |
| 469 |
func (d *decoderState) ReadToken() (Token, error) { |
| 470 |
// Determine the next kind. |
| 471 |
var err error |
| 472 |
var next Kind |
| 473 |
pos := d.peekPos |
| 474 |
if pos != 0 { |
| 475 |
// Use cached peek result. |
| 476 |
if d.peekErr != nil { |
| 477 |
err := d.peekErr |
| 478 |
d.peekPos, d.peekErr = 0, nil // possibly a transient I/O error |
| 479 |
return Token{}, err |
| 480 |
} |
| 481 |
next = Kind(d.buf[pos]).normalize() |
| 482 |
d.peekPos = 0 // reset cache |
| 483 |
} else { |
| 484 |
d.invalidatePreviousRead() |
| 485 |
pos = d.prevEnd |
| 486 |
|
| 487 |
// Consume leading whitespace. |
| 488 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 489 |
if d.needMore(pos) { |
| 490 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 491 |
if err == io.ErrUnexpectedEOF && d.Tokens.Depth() == 1 { |
| 492 |
err = io.EOF // EOF possibly if no Tokens present after top-level value |
| 493 |
} |
| 494 |
return Token{}, wrapSyntacticError(d, err, pos, 0) |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
// Consume colon or comma. |
| 499 |
var delim byte |
| 500 |
if c := d.buf[pos]; c == ':' || c == ',' { |
| 501 |
delim = c |
| 502 |
pos += 1 |
| 503 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 504 |
if d.needMore(pos) { |
| 505 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 506 |
err = wrapSyntacticError(d, err, pos, 0) |
| 507 |
return Token{}, d.checkDelimBeforeIOError(delim, err) |
| 508 |
} |
| 509 |
} |
| 510 |
} |
| 511 |
next = Kind(d.buf[pos]).normalize() |
| 512 |
if d.Tokens.needDelim(next) != delim { |
| 513 |
return Token{}, d.checkDelim(delim, next) |
| 514 |
} |
| 515 |
} |
| 516 |
|
| 517 |
// Handle the next token. |
| 518 |
var n int |
| 519 |
switch next { |
| 520 |
case 'n': |
| 521 |
if jsonwire.ConsumeNull(d.buf[pos:]) == 0 { |
| 522 |
pos, err = d.consumeLiteral(pos, "null") |
| 523 |
if err != nil { |
| 524 |
return Token{}, wrapSyntacticError(d, err, pos, +1) |
| 525 |
} |
| 526 |
} else { |
| 527 |
pos += len("null") |
| 528 |
} |
| 529 |
if err = d.Tokens.appendLiteral(); err != nil { |
| 530 |
return Token{}, wrapSyntacticError(d, err, pos-len("null"), +1) // report position at start of literal |
| 531 |
} |
| 532 |
d.prevStart, d.prevEnd = pos, pos |
| 533 |
return Null, nil |
| 534 |
|
| 535 |
case 'f': |
| 536 |
if jsonwire.ConsumeFalse(d.buf[pos:]) == 0 { |
| 537 |
pos, err = d.consumeLiteral(pos, "false") |
| 538 |
if err != nil { |
| 539 |
return Token{}, wrapSyntacticError(d, err, pos, +1) |
| 540 |
} |
| 541 |
} else { |
| 542 |
pos += len("false") |
| 543 |
} |
| 544 |
if err = d.Tokens.appendLiteral(); err != nil { |
| 545 |
return Token{}, wrapSyntacticError(d, err, pos-len("false"), +1) // report position at start of literal |
| 546 |
} |
| 547 |
d.prevStart, d.prevEnd = pos, pos |
| 548 |
return False, nil |
| 549 |
|
| 550 |
case 't': |
| 551 |
if jsonwire.ConsumeTrue(d.buf[pos:]) == 0 { |
| 552 |
pos, err = d.consumeLiteral(pos, "true") |
| 553 |
if err != nil { |
| 554 |
return Token{}, wrapSyntacticError(d, err, pos, +1) |
| 555 |
} |
| 556 |
} else { |
| 557 |
pos += len("true") |
| 558 |
} |
| 559 |
if err = d.Tokens.appendLiteral(); err != nil { |
| 560 |
return Token{}, wrapSyntacticError(d, err, pos-len("true"), +1) // report position at start of literal |
| 561 |
} |
| 562 |
d.prevStart, d.prevEnd = pos, pos |
| 563 |
return True, nil |
| 564 |
|
| 565 |
case '"': |
| 566 |
var flags jsonwire.ValueFlags // TODO: Preserve this in Token? |
| 567 |
if n = jsonwire.ConsumeSimpleString(d.buf[pos:]); n == 0 { |
| 568 |
oldAbsPos := d.baseOffset + int64(pos) |
| 569 |
pos, err = d.consumeString(&flags, pos) |
| 570 |
newAbsPos := d.baseOffset + int64(pos) |
| 571 |
n = int(newAbsPos - oldAbsPos) |
| 572 |
if err != nil { |
| 573 |
return Token{}, wrapSyntacticError(d, err, pos, +1) |
| 574 |
} |
| 575 |
} else { |
| 576 |
pos += n |
| 577 |
} |
| 578 |
if d.Tokens.Last.NeedObjectName() { |
| 579 |
if !d.Flags.Get(jsonflags.AllowDuplicateNames) { |
| 580 |
if !d.Tokens.Last.isValidNamespace() { |
| 581 |
return Token{}, wrapSyntacticError(d, errInvalidNamespace, pos-n, +1) |
| 582 |
} |
| 583 |
if d.Tokens.Last.isActiveNamespace() && !d.Namespaces.Last().insertQuoted(d.buf[pos-n:pos], flags.IsVerbatim()) { |
| 584 |
err = wrapWithObjectName(ErrDuplicateName, d.buf[pos-n:pos]) |
| 585 |
return Token{}, wrapSyntacticError(d, err, pos-n, +1) // report position at start of string |
| 586 |
} |
| 587 |
} |
| 588 |
d.Names.ReplaceLastQuotedOffset(pos - n) // only replace if insertQuoted succeeds |
| 589 |
} |
| 590 |
if err = d.Tokens.appendString(); err != nil { |
| 591 |
return Token{}, wrapSyntacticError(d, err, pos-n, +1) // report position at start of string |
| 592 |
} |
| 593 |
d.prevStart, d.prevEnd = pos-n, pos |
| 594 |
return Token{raw: &d.decodeBuffer, num: uint64(d.previousOffsetStart())}, nil |
| 595 |
|
| 596 |
case '0': |
| 597 |
// NOTE: Since JSON numbers are not self-terminating, |
| 598 |
// we need to make sure that the next byte is not part of a number. |
| 599 |
if n = jsonwire.ConsumeSimpleNumber(d.buf[pos:]); n == 0 || d.needMore(pos+n) { |
| 600 |
oldAbsPos := d.baseOffset + int64(pos) |
| 601 |
pos, err = d.consumeNumber(pos) |
| 602 |
newAbsPos := d.baseOffset + int64(pos) |
| 603 |
n = int(newAbsPos - oldAbsPos) |
| 604 |
if err != nil { |
| 605 |
return Token{}, wrapSyntacticError(d, err, pos, +1) |
| 606 |
} |
| 607 |
} else { |
| 608 |
pos += n |
| 609 |
} |
| 610 |
if err = d.Tokens.appendNumber(); err != nil { |
| 611 |
return Token{}, wrapSyntacticError(d, err, pos-n, +1) // report position at start of number |
| 612 |
} |
| 613 |
d.prevStart, d.prevEnd = pos-n, pos |
| 614 |
return Token{raw: &d.decodeBuffer, num: uint64(d.previousOffsetStart())}, nil |
| 615 |
|
| 616 |
case '{': |
| 617 |
if err = d.Tokens.pushObject(); err != nil { |
| 618 |
return Token{}, wrapSyntacticError(d, err, pos, +1) |
| 619 |
} |
| 620 |
d.Names.push() |
| 621 |
if !d.Flags.Get(jsonflags.AllowDuplicateNames) { |
| 622 |
d.Namespaces.push() |
| 623 |
} |
| 624 |
pos += 1 |
| 625 |
d.prevStart, d.prevEnd = pos, pos |
| 626 |
return BeginObject, nil |
| 627 |
|
| 628 |
case '}': |
| 629 |
if err = d.Tokens.popObject(); err != nil { |
| 630 |
return Token{}, wrapSyntacticError(d, err, pos, +1) |
| 631 |
} |
| 632 |
d.Names.pop() |
| 633 |
if !d.Flags.Get(jsonflags.AllowDuplicateNames) { |
| 634 |
d.Namespaces.pop() |
| 635 |
} |
| 636 |
pos += 1 |
| 637 |
d.prevStart, d.prevEnd = pos, pos |
| 638 |
return EndObject, nil |
| 639 |
|
| 640 |
case '[': |
| 641 |
if err = d.Tokens.pushArray(); err != nil { |
| 642 |
return Token{}, wrapSyntacticError(d, err, pos, +1) |
| 643 |
} |
| 644 |
pos += 1 |
| 645 |
d.prevStart, d.prevEnd = pos, pos |
| 646 |
return BeginArray, nil |
| 647 |
|
| 648 |
case ']': |
| 649 |
if err = d.Tokens.popArray(); err != nil { |
| 650 |
return Token{}, wrapSyntacticError(d, err, pos, +1) |
| 651 |
} |
| 652 |
pos += 1 |
| 653 |
d.prevStart, d.prevEnd = pos, pos |
| 654 |
return EndArray, nil |
| 655 |
|
| 656 |
default: |
| 657 |
err = jsonwire.NewInvalidCharacterError(d.buf[pos:], "at start of value") |
| 658 |
return Token{}, wrapSyntacticError(d, err, pos, +1) |
| 659 |
} |
| 660 |
} |
| 661 |
|
| 662 |
// ReadValue returns the next raw JSON value, advancing the read offset. |
| 663 |
// The value is stripped of any leading or trailing whitespace and |
| 664 |
// contains the exact bytes of the input, which may contain invalid UTF-8 |
| 665 |
// if [AllowInvalidUTF8] is specified. |
| 666 |
// |
| 667 |
// The returned value is only valid until the next Peek, Read, or Skip call and |
| 668 |
// may not be mutated while the Decoder remains in use. |
| 669 |
// If the decoder is currently at the end token for an object or array, |
| 670 |
// then it reports a [SyntacticError] and the internal state remains unchanged. |
| 671 |
// It returns [io.EOF] if there are no more values. |
| 672 |
func (d *Decoder) ReadValue() (Value, error) { |
| 673 |
var flags jsonwire.ValueFlags |
| 674 |
return d.s.ReadValue(&flags) |
| 675 |
} |
| 676 |
func (d *decoderState) ReadValue(flags *jsonwire.ValueFlags) (Value, error) { |
| 677 |
// Determine the next kind. |
| 678 |
var err error |
| 679 |
var next Kind |
| 680 |
pos := d.peekPos |
| 681 |
if pos != 0 { |
| 682 |
// Use cached peek result. |
| 683 |
if d.peekErr != nil { |
| 684 |
err := d.peekErr |
| 685 |
d.peekPos, d.peekErr = 0, nil // possibly a transient I/O error |
| 686 |
return nil, err |
| 687 |
} |
| 688 |
next = Kind(d.buf[pos]).normalize() |
| 689 |
d.peekPos = 0 // reset cache |
| 690 |
} else { |
| 691 |
d.invalidatePreviousRead() |
| 692 |
pos = d.prevEnd |
| 693 |
|
| 694 |
// Consume leading whitespace. |
| 695 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 696 |
if d.needMore(pos) { |
| 697 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 698 |
if err == io.ErrUnexpectedEOF && d.Tokens.Depth() == 1 { |
| 699 |
err = io.EOF // EOF possibly if no Tokens present after top-level value |
| 700 |
} |
| 701 |
return nil, wrapSyntacticError(d, err, pos, 0) |
| 702 |
} |
| 703 |
} |
| 704 |
|
| 705 |
// Consume colon or comma. |
| 706 |
var delim byte |
| 707 |
if c := d.buf[pos]; c == ':' || c == ',' { |
| 708 |
delim = c |
| 709 |
pos += 1 |
| 710 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 711 |
if d.needMore(pos) { |
| 712 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 713 |
err = wrapSyntacticError(d, err, pos, 0) |
| 714 |
return nil, d.checkDelimBeforeIOError(delim, err) |
| 715 |
} |
| 716 |
} |
| 717 |
} |
| 718 |
next = Kind(d.buf[pos]).normalize() |
| 719 |
if d.Tokens.needDelim(next) != delim { |
| 720 |
return nil, d.checkDelim(delim, next) |
| 721 |
} |
| 722 |
} |
| 723 |
|
| 724 |
// Handle the next value. |
| 725 |
oldAbsPos := d.baseOffset + int64(pos) |
| 726 |
pos, err = d.consumeValue(flags, pos, d.Tokens.Depth()) |
| 727 |
newAbsPos := d.baseOffset + int64(pos) |
| 728 |
n := int(newAbsPos - oldAbsPos) |
| 729 |
if err != nil { |
| 730 |
return nil, wrapSyntacticError(d, err, pos, +1) |
| 731 |
} |
| 732 |
switch next { |
| 733 |
case 'n', 't', 'f': |
| 734 |
err = d.Tokens.appendLiteral() |
| 735 |
case '"': |
| 736 |
if d.Tokens.Last.NeedObjectName() { |
| 737 |
if !d.Flags.Get(jsonflags.AllowDuplicateNames) { |
| 738 |
if !d.Tokens.Last.isValidNamespace() { |
| 739 |
err = errInvalidNamespace |
| 740 |
break |
| 741 |
} |
| 742 |
if d.Tokens.Last.isActiveNamespace() && !d.Namespaces.Last().insertQuoted(d.buf[pos-n:pos], flags.IsVerbatim()) { |
| 743 |
err = wrapWithObjectName(ErrDuplicateName, d.buf[pos-n:pos]) |
| 744 |
break |
| 745 |
} |
| 746 |
} |
| 747 |
d.Names.ReplaceLastQuotedOffset(pos - n) // only replace if insertQuoted succeeds |
| 748 |
} |
| 749 |
err = d.Tokens.appendString() |
| 750 |
case '0': |
| 751 |
err = d.Tokens.appendNumber() |
| 752 |
case '{': |
| 753 |
if err = d.Tokens.pushObject(); err != nil { |
| 754 |
break |
| 755 |
} |
| 756 |
if err = d.Tokens.popObject(); err != nil { |
| 757 |
panic("BUG: popObject should never fail immediately after pushObject: " + err.Error()) |
| 758 |
} |
| 759 |
case '[': |
| 760 |
if err = d.Tokens.pushArray(); err != nil { |
| 761 |
break |
| 762 |
} |
| 763 |
if err = d.Tokens.popArray(); err != nil { |
| 764 |
panic("BUG: popArray should never fail immediately after pushArray: " + err.Error()) |
| 765 |
} |
| 766 |
} |
| 767 |
if err != nil { |
| 768 |
return nil, wrapSyntacticError(d, err, pos-n, +1) // report position at start of value |
| 769 |
} |
| 770 |
d.prevEnd = pos |
| 771 |
d.prevStart = pos - n |
| 772 |
return d.buf[pos-n : pos : pos], nil |
| 773 |
} |
| 774 |
|
| 775 |
// CheckNextValue checks whether the next value is syntactically valid, |
| 776 |
// but does not advance the read offset. |
| 777 |
// If last, it verifies that the stream cleanly terminates with [io.EOF]. |
| 778 |
func (d *decoderState) CheckNextValue(last bool) error { |
| 779 |
d.PeekKind() // populates d.peekPos and d.peekErr |
| 780 |
pos, err := d.peekPos, d.peekErr |
| 781 |
d.peekPos, d.peekErr = 0, nil |
| 782 |
if err != nil { |
| 783 |
return err |
| 784 |
} |
| 785 |
|
| 786 |
var flags jsonwire.ValueFlags |
| 787 |
if pos, err := d.consumeValue(&flags, pos, d.Tokens.Depth()); err != nil { |
| 788 |
return wrapSyntacticError(d, err, pos, +1) |
| 789 |
} else if last { |
| 790 |
return d.checkEOF(pos) |
| 791 |
} |
| 792 |
return nil |
| 793 |
} |
| 794 |
|
| 795 |
// AtEOF reports whether the decoder is at EOF. |
| 796 |
func (d *decoderState) AtEOF() bool { |
| 797 |
_, err := d.consumeWhitespace(d.prevEnd) |
| 798 |
return err == io.ErrUnexpectedEOF |
| 799 |
} |
| 800 |
|
| 801 |
// CheckEOF verifies that the input has no more data. |
| 802 |
func (d *decoderState) CheckEOF() error { |
| 803 |
return d.checkEOF(d.prevEnd) |
| 804 |
} |
| 805 |
func (d *decoderState) checkEOF(pos int) error { |
| 806 |
switch pos, err := d.consumeWhitespace(pos); err { |
| 807 |
case nil: |
| 808 |
err := jsonwire.NewInvalidCharacterError(d.buf[pos:], "after top-level value") |
| 809 |
return wrapSyntacticError(d, err, pos, 0) |
| 810 |
case io.ErrUnexpectedEOF: |
| 811 |
return nil |
| 812 |
default: |
| 813 |
return err |
| 814 |
} |
| 815 |
} |
| 816 |
|
| 817 |
// consumeWhitespace consumes all whitespace starting at d.buf[pos:]. |
| 818 |
// It returns the new position in d.buf immediately after the last whitespace. |
| 819 |
// If it returns nil, there is guaranteed to at least be one unread byte. |
| 820 |
// |
| 821 |
// The following pattern is common in this implementation: |
| 822 |
// |
| 823 |
// pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 824 |
// if d.needMore(pos) { |
| 825 |
// if pos, err = d.consumeWhitespace(pos); err != nil { |
| 826 |
// return ... |
| 827 |
// } |
| 828 |
// } |
| 829 |
// |
| 830 |
// It is difficult to simplify this without sacrificing performance since |
| 831 |
// consumeWhitespace must be inlined. The body of the if statement is |
| 832 |
// executed only in rare situations where we need to fetch more data. |
| 833 |
// Since fetching may return an error, we also need to check the error. |
| 834 |
func (d *decoderState) consumeWhitespace(pos int) (newPos int, err error) { |
| 835 |
for { |
| 836 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 837 |
if d.needMore(pos) { |
| 838 |
absPos := d.baseOffset + int64(pos) |
| 839 |
err = d.fetch() // will mutate d.buf and invalidate pos |
| 840 |
pos = int(absPos - d.baseOffset) |
| 841 |
if err != nil { |
| 842 |
return pos, err |
| 843 |
} |
| 844 |
continue |
| 845 |
} |
| 846 |
return pos, nil |
| 847 |
} |
| 848 |
} |
| 849 |
|
| 850 |
// consumeValue consumes a single JSON value starting at d.buf[pos:]. |
| 851 |
// It returns the new position in d.buf immediately after the value. |
| 852 |
func (d *decoderState) consumeValue(flags *jsonwire.ValueFlags, pos, depth int) (newPos int, err error) { |
| 853 |
for { |
| 854 |
var n int |
| 855 |
var err error |
| 856 |
switch next := Kind(d.buf[pos]).normalize(); next { |
| 857 |
case 'n': |
| 858 |
if n = jsonwire.ConsumeNull(d.buf[pos:]); n == 0 { |
| 859 |
n, err = jsonwire.ConsumeLiteral(d.buf[pos:], "null") |
| 860 |
} |
| 861 |
case 'f': |
| 862 |
if n = jsonwire.ConsumeFalse(d.buf[pos:]); n == 0 { |
| 863 |
n, err = jsonwire.ConsumeLiteral(d.buf[pos:], "false") |
| 864 |
} |
| 865 |
case 't': |
| 866 |
if n = jsonwire.ConsumeTrue(d.buf[pos:]); n == 0 { |
| 867 |
n, err = jsonwire.ConsumeLiteral(d.buf[pos:], "true") |
| 868 |
} |
| 869 |
case '"': |
| 870 |
if n = jsonwire.ConsumeSimpleString(d.buf[pos:]); n == 0 { |
| 871 |
return d.consumeString(flags, pos) |
| 872 |
} |
| 873 |
case '0': |
| 874 |
// NOTE: Since JSON numbers are not self-terminating, |
| 875 |
// we need to make sure that the next byte is not part of a number. |
| 876 |
if n = jsonwire.ConsumeSimpleNumber(d.buf[pos:]); n == 0 || d.needMore(pos+n) { |
| 877 |
return d.consumeNumber(pos) |
| 878 |
} |
| 879 |
case '{': |
| 880 |
return d.consumeObject(flags, pos, depth) |
| 881 |
case '[': |
| 882 |
return d.consumeArray(flags, pos, depth) |
| 883 |
default: |
| 884 |
if (d.Tokens.Last.isObject() && next == ']') || (d.Tokens.Last.isArray() && next == '}') { |
| 885 |
return pos, errMismatchDelim |
| 886 |
} |
| 887 |
return pos, jsonwire.NewInvalidCharacterError(d.buf[pos:], "at start of value") |
| 888 |
} |
| 889 |
if err == io.ErrUnexpectedEOF { |
| 890 |
absPos := d.baseOffset + int64(pos) |
| 891 |
err = d.fetch() // will mutate d.buf and invalidate pos |
| 892 |
pos = int(absPos - d.baseOffset) |
| 893 |
if err != nil { |
| 894 |
return pos + n, err |
| 895 |
} |
| 896 |
continue |
| 897 |
} |
| 898 |
return pos + n, err |
| 899 |
} |
| 900 |
} |
| 901 |
|
| 902 |
// consumeLiteral consumes a single JSON literal starting at d.buf[pos:]. |
| 903 |
// It returns the new position in d.buf immediately after the literal. |
| 904 |
func (d *decoderState) consumeLiteral(pos int, lit string) (newPos int, err error) { |
| 905 |
for { |
| 906 |
n, err := jsonwire.ConsumeLiteral(d.buf[pos:], lit) |
| 907 |
if err == io.ErrUnexpectedEOF { |
| 908 |
absPos := d.baseOffset + int64(pos) |
| 909 |
err = d.fetch() // will mutate d.buf and invalidate pos |
| 910 |
pos = int(absPos - d.baseOffset) |
| 911 |
if err != nil { |
| 912 |
return pos + n, err |
| 913 |
} |
| 914 |
continue |
| 915 |
} |
| 916 |
return pos + n, err |
| 917 |
} |
| 918 |
} |
| 919 |
|
| 920 |
// consumeString consumes a single JSON string starting at d.buf[pos:]. |
| 921 |
// It returns the new position in d.buf immediately after the string. |
| 922 |
func (d *decoderState) consumeString(flags *jsonwire.ValueFlags, pos int) (newPos int, err error) { |
| 923 |
var n int |
| 924 |
for { |
| 925 |
n, err = jsonwire.ConsumeStringResumable(flags, d.buf[pos:], n, !d.Flags.Get(jsonflags.AllowInvalidUTF8)) |
| 926 |
if err == io.ErrUnexpectedEOF { |
| 927 |
absPos := d.baseOffset + int64(pos) |
| 928 |
err = d.fetch() // will mutate d.buf and invalidate pos |
| 929 |
pos = int(absPos - d.baseOffset) |
| 930 |
if err != nil { |
| 931 |
return pos + n, err |
| 932 |
} |
| 933 |
continue |
| 934 |
} |
| 935 |
return pos + n, err |
| 936 |
} |
| 937 |
} |
| 938 |
|
| 939 |
// consumeNumber consumes a single JSON number starting at d.buf[pos:]. |
| 940 |
// It returns the new position in d.buf immediately after the number. |
| 941 |
func (d *decoderState) consumeNumber(pos int) (newPos int, err error) { |
| 942 |
var n int |
| 943 |
var state jsonwire.ConsumeNumberState |
| 944 |
for { |
| 945 |
n, state, err = jsonwire.ConsumeNumberResumable(d.buf[pos:], n, state) |
| 946 |
// NOTE: Since JSON numbers are not self-terminating, |
| 947 |
// we need to make sure that the next byte is not part of a number. |
| 948 |
if err == io.ErrUnexpectedEOF || d.needMore(pos+n) { |
| 949 |
mayTerminate := err == nil |
| 950 |
absPos := d.baseOffset + int64(pos) |
| 951 |
err = d.fetch() // will mutate d.buf and invalidate pos |
| 952 |
pos = int(absPos - d.baseOffset) |
| 953 |
if err != nil { |
| 954 |
if mayTerminate && err == io.ErrUnexpectedEOF { |
| 955 |
return pos + n, nil |
| 956 |
} |
| 957 |
return pos, err |
| 958 |
} |
| 959 |
continue |
| 960 |
} |
| 961 |
return pos + n, err |
| 962 |
} |
| 963 |
} |
| 964 |
|
| 965 |
// consumeObject consumes a single JSON object starting at d.buf[pos:]. |
| 966 |
// It returns the new position in d.buf immediately after the object. |
| 967 |
func (d *decoderState) consumeObject(flags *jsonwire.ValueFlags, pos, depth int) (newPos int, err error) { |
| 968 |
var n int |
| 969 |
var names *objectNamespace |
| 970 |
if !d.Flags.Get(jsonflags.AllowDuplicateNames) { |
| 971 |
d.Namespaces.push() |
| 972 |
defer d.Namespaces.pop() |
| 973 |
names = d.Namespaces.Last() |
| 974 |
} |
| 975 |
|
| 976 |
// Handle before start. |
| 977 |
if uint(pos) >= uint(len(d.buf)) || d.buf[pos] != '{' { |
| 978 |
panic("BUG: consumeObject must be called with a buffer that starts with '{'") |
| 979 |
} else if depth == maxNestingDepth+1 { |
| 980 |
return pos, errMaxDepth |
| 981 |
} |
| 982 |
pos++ |
| 983 |
|
| 984 |
// Handle after start. |
| 985 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 986 |
if d.needMore(pos) { |
| 987 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 988 |
return pos, err |
| 989 |
} |
| 990 |
} |
| 991 |
if d.buf[pos] == '}' { |
| 992 |
pos++ |
| 993 |
return pos, nil |
| 994 |
} |
| 995 |
|
| 996 |
depth++ |
| 997 |
for { |
| 998 |
// Handle before name. |
| 999 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 1000 |
if d.needMore(pos) { |
| 1001 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 1002 |
return pos, err |
| 1003 |
} |
| 1004 |
} |
| 1005 |
var flags2 jsonwire.ValueFlags |
| 1006 |
if n = jsonwire.ConsumeSimpleString(d.buf[pos:]); n == 0 { |
| 1007 |
oldAbsPos := d.baseOffset + int64(pos) |
| 1008 |
pos, err = d.consumeString(&flags2, pos) |
| 1009 |
newAbsPos := d.baseOffset + int64(pos) |
| 1010 |
n = int(newAbsPos - oldAbsPos) |
| 1011 |
flags.Join(flags2) |
| 1012 |
if err != nil { |
| 1013 |
return pos, err |
| 1014 |
} |
| 1015 |
} else { |
| 1016 |
pos += n |
| 1017 |
} |
| 1018 |
quotedName := d.buf[pos-n : pos] |
| 1019 |
if !d.Flags.Get(jsonflags.AllowDuplicateNames) && !names.insertQuoted(quotedName, flags2.IsVerbatim()) { |
| 1020 |
return pos - n, wrapWithObjectName(ErrDuplicateName, quotedName) |
| 1021 |
} |
| 1022 |
|
| 1023 |
// Handle after name. |
| 1024 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 1025 |
if d.needMore(pos) { |
| 1026 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 1027 |
return pos, wrapWithObjectName(err, quotedName) |
| 1028 |
} |
| 1029 |
} |
| 1030 |
if d.buf[pos] != ':' { |
| 1031 |
err := jsonwire.NewInvalidCharacterError(d.buf[pos:], "after object name (expecting ':')") |
| 1032 |
return pos, wrapWithObjectName(err, quotedName) |
| 1033 |
} |
| 1034 |
pos++ |
| 1035 |
|
| 1036 |
// Handle before value. |
| 1037 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 1038 |
if d.needMore(pos) { |
| 1039 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 1040 |
return pos, wrapWithObjectName(err, quotedName) |
| 1041 |
} |
| 1042 |
} |
| 1043 |
pos, err = d.consumeValue(flags, pos, depth) |
| 1044 |
if err != nil { |
| 1045 |
return pos, wrapWithObjectName(err, quotedName) |
| 1046 |
} |
| 1047 |
|
| 1048 |
// Handle after value. |
| 1049 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 1050 |
if d.needMore(pos) { |
| 1051 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 1052 |
return pos, err |
| 1053 |
} |
| 1054 |
} |
| 1055 |
switch d.buf[pos] { |
| 1056 |
case ',': |
| 1057 |
pos++ |
| 1058 |
continue |
| 1059 |
case '}': |
| 1060 |
pos++ |
| 1061 |
return pos, nil |
| 1062 |
default: |
| 1063 |
return pos, jsonwire.NewInvalidCharacterError(d.buf[pos:], "after object value (expecting ',' or '}')") |
| 1064 |
} |
| 1065 |
} |
| 1066 |
} |
| 1067 |
|
| 1068 |
// consumeArray consumes a single JSON array starting at d.buf[pos:]. |
| 1069 |
// It returns the new position in d.buf immediately after the array. |
| 1070 |
func (d *decoderState) consumeArray(flags *jsonwire.ValueFlags, pos, depth int) (newPos int, err error) { |
| 1071 |
// Handle before start. |
| 1072 |
if uint(pos) >= uint(len(d.buf)) || d.buf[pos] != '[' { |
| 1073 |
panic("BUG: consumeArray must be called with a buffer that starts with '['") |
| 1074 |
} else if depth == maxNestingDepth+1 { |
| 1075 |
return pos, errMaxDepth |
| 1076 |
} |
| 1077 |
pos++ |
| 1078 |
|
| 1079 |
// Handle after start. |
| 1080 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 1081 |
if d.needMore(pos) { |
| 1082 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 1083 |
return pos, err |
| 1084 |
} |
| 1085 |
} |
| 1086 |
if d.buf[pos] == ']' { |
| 1087 |
pos++ |
| 1088 |
return pos, nil |
| 1089 |
} |
| 1090 |
|
| 1091 |
var idx int64 |
| 1092 |
depth++ |
| 1093 |
for { |
| 1094 |
// Handle before value. |
| 1095 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 1096 |
if d.needMore(pos) { |
| 1097 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 1098 |
return pos, err |
| 1099 |
} |
| 1100 |
} |
| 1101 |
pos, err = d.consumeValue(flags, pos, depth) |
| 1102 |
if err != nil { |
| 1103 |
return pos, wrapWithArrayIndex(err, idx) |
| 1104 |
} |
| 1105 |
|
| 1106 |
// Handle after value. |
| 1107 |
pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) |
| 1108 |
if d.needMore(pos) { |
| 1109 |
if pos, err = d.consumeWhitespace(pos); err != nil { |
| 1110 |
return pos, err |
| 1111 |
} |
| 1112 |
} |
| 1113 |
switch d.buf[pos] { |
| 1114 |
case ',': |
| 1115 |
pos++ |
| 1116 |
idx++ |
| 1117 |
continue |
| 1118 |
case ']': |
| 1119 |
pos++ |
| 1120 |
return pos, nil |
| 1121 |
default: |
| 1122 |
return pos, jsonwire.NewInvalidCharacterError(d.buf[pos:], "after array element (expecting ',' or ']')") |
| 1123 |
} |
| 1124 |
} |
| 1125 |
} |
| 1126 |
|
| 1127 |
// InputOffset returns the current input byte offset. It gives the location |
| 1128 |
// of the next byte immediately after the most recently returned token or value. |
| 1129 |
// The number of bytes actually read from the underlying [io.Reader] may be more |
| 1130 |
// than this offset due to internal buffering effects. |
| 1131 |
func (d *Decoder) InputOffset() int64 { |
| 1132 |
return d.s.previousOffsetEnd() |
| 1133 |
} |
| 1134 |
|
| 1135 |
// UnreadBuffer returns the data remaining in the unread buffer, |
| 1136 |
// which may contain zero or more bytes. |
| 1137 |
// The returned buffer must not be mutated while Decoder continues to be used. |
| 1138 |
// The buffer contents are valid until the next Peek, Read, or Skip call. |
| 1139 |
func (d *Decoder) UnreadBuffer() []byte { |
| 1140 |
return d.s.unreadBuffer() |
| 1141 |
} |
| 1142 |
|
| 1143 |
// StackDepth returns the depth of the state machine for read JSON data. |
| 1144 |
// Each level on the stack represents a nested JSON object or array. |
| 1145 |
// It is incremented whenever an [BeginObject] or [BeginArray] token is encountered |
| 1146 |
// and decremented whenever an [EndObject] or [EndArray] token is encountered. |
| 1147 |
// The depth is zero-indexed, where zero represents the top-level JSON value. |
| 1148 |
func (d *Decoder) StackDepth() int { |
| 1149 |
// NOTE: Keep in sync with Encoder.StackDepth. |
| 1150 |
return d.s.Tokens.Depth() - 1 |
| 1151 |
} |
| 1152 |
|
| 1153 |
// StackIndex returns information about the specified stack level. |
| 1154 |
// It must be a number between 0 and [Decoder.StackDepth], inclusive. |
| 1155 |
// For each level, it reports the kind: |
| 1156 |
// |
| 1157 |
// - [KindInvalid] for a level of zero, |
| 1158 |
// - [KindBeginObject] for a level representing a JSON object, and |
| 1159 |
// - [KindBeginArray] for a level representing a JSON array. |
| 1160 |
// |
| 1161 |
// It also reports the length of that JSON object or array. |
| 1162 |
// Each name and value in a JSON object is counted separately, |
| 1163 |
// so the effective number of members would be half the length. |
| 1164 |
// A complete JSON object must have an even length. |
| 1165 |
func (d *Decoder) StackIndex(i int) (Kind, int64) { |
| 1166 |
// NOTE: Keep in sync with Encoder.StackIndex. |
| 1167 |
switch s := d.s.Tokens.index(i); { |
| 1168 |
case i > 0 && s.isObject(): |
| 1169 |
return '{', s.Length() |
| 1170 |
case i > 0 && s.isArray(): |
| 1171 |
return '[', s.Length() |
| 1172 |
default: |
| 1173 |
return 0, s.Length() |
| 1174 |
} |
| 1175 |
} |
| 1176 |
|
| 1177 |
// StackPointer returns a JSON Pointer (RFC 6901) to the most recently read value. |
| 1178 |
func (d *Decoder) StackPointer() Pointer { |
| 1179 |
return Pointer(d.s.AppendStackPointer(nil, -1)) |
| 1180 |
} |
| 1181 |
|
| 1182 |
func (d *decoderState) AppendStackPointer(b []byte, where int) []byte { |
| 1183 |
d.Names.copyQuotedBuffer(d.buf) |
| 1184 |
return d.state.appendStackPointer(b, where) |
| 1185 |
} |