Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/jsontext/state.go

raw
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 package jsontext
6
7 import (
8 "errors"
9 "iter"
10 "math"
11 "strconv"
12 "strings"
13 "unicode/utf8"
14
15 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
16 )
17
18 // ErrDuplicateName indicates that a JSON token could not be
19 // encoded or decoded because it results in a duplicate JSON object name.
20 // This error is directly wrapped within a [SyntacticError] when produced.
21 //
22 // The name of a duplicate JSON object member can be extracted as:
23 //
24 // err := ...
25 // var serr jsontext.SyntacticError
26 // if errors.As(err, &serr) && serr.Err == jsontext.ErrDuplicateName {
27 // ptr := serr.JSONPointer // JSON pointer to duplicate name
28 // name := ptr.LastToken() // duplicate name itself
29 // ...
30 // }
31 //
32 // This error is only returned if [AllowDuplicateNames] is false.
33 var ErrDuplicateName = errors.New("duplicate object member name")
34
35 // ErrNonStringName indicates that a JSON token could not be
36 // encoded or decoded because it is not a string,
37 // as required for JSON object names according to RFC 8259, section 4.
38 // This error is directly wrapped within a [SyntacticError] when produced.
39 var ErrNonStringName = errors.New("object member name must be a string")
40
41 var (
42 errMissingValue = errors.New("missing value after object name")
43 errMismatchDelim = errors.New("mismatching structural token for object or array")
44 errMaxDepth = errors.New("exceeded max depth")
45
46 errInvalidNamespace = errors.New("object namespace is in an invalid state")
47 )
48
49 // Per RFC 8259, section 9, implementations may enforce a maximum depth.
50 // Such a limit is necessary to prevent stack overflows.
51 const maxNestingDepth = 10000
52
53 type state struct {
54 // Tokens validates whether the next token kind is valid.
55 Tokens stateMachine
56
57 // Names is a stack of object names.
58 Names objectNameStack
59
60 // Namespaces is a stack of object namespaces.
61 // For performance reasons, Encoder or Decoder may not update this
62 // if Marshal or Unmarshal is able to track names in a more efficient way.
63 // See makeMapArshaler and makeStructArshaler.
64 // Not used if AllowDuplicateNames is true.
65 Namespaces objectNamespaceStack
66 }
67
68 // needObjectValue reports whether the next token should be an object value.
69 // This method is used by [wrapSyntacticError].
70 func (s *state) needObjectValue() bool {
71 return s.Tokens.Last.needObjectValue()
72 }
73
74 func (s *state) reset() {
75 s.Tokens.reset()
76 s.Names.reset()
77 s.Namespaces.reset()
78 }
79
80 // Pointer is a JSON Pointer (RFC 6901) that references a particular JSON value
81 // relative to the root of the top-level JSON value.
82 //
83 // A Pointer is a slash-separated list of tokens, where each token is
84 // either a JSON object name or an index to a JSON array element
85 // encoded as a base-10 integer value.
86 // It is impossible to distinguish between an array index and an object name
87 // (that happens to be an base-10 encoded integer) without also knowing
88 // the structure of the top-level JSON value that the pointer refers to.
89 //
90 // There is exactly one representation of a pointer to a particular value,
91 // so comparability of Pointer values is equivalent to checking whether
92 // they both point to the exact same value.
93 type Pointer string
94
95 // IsValid reports whether p is a valid JSON Pointer according to RFC 6901.
96 // Note that the concatenation of two valid pointers produces a valid pointer.
97 func (p Pointer) IsValid() bool {
98 for i, r := range p {
99 switch {
100 case r == '~' && (i+1 == len(p) || (p[i+1] != '0' && p[i+1] != '1')):
101 return false // invalid escape
102 case r == '\ufffd' && !strings.HasPrefix(string(p[i:]), "\ufffd"):
103 return false // invalid UTF-8
104 }
105 }
106 return len(p) == 0 || p[0] == '/'
107 }
108
109 // Contains reports whether the JSON value that p points to
110 // is equal to or contains the JSON value that pc points to.
111 func (p Pointer) Contains(pc Pointer) bool {
112 // Invariant: len(p) <= len(pc) if p.Contains(pc)
113 suffix, ok := strings.CutPrefix(string(pc), string(p))
114 return ok && (suffix == "" || suffix[0] == '/')
115 }
116
117 // Parent strips off the last token and returns the remaining pointer.
118 // The parent of an empty p is an empty string.
119 func (p Pointer) Parent() Pointer {
120 return p[:max(strings.LastIndexByte(string(p), '/'), 0)]
121 }
122
123 // LastToken returns the last token in the pointer.
124 // The last token of an empty p is an empty string.
125 func (p Pointer) LastToken() string {
126 last := p[max(strings.LastIndexByte(string(p), '/'), 0):]
127 return unescapePointerToken(strings.TrimPrefix(string(last), "/"))
128 }
129
130 // AppendToken appends a token to the end of p and returns the full pointer.
131 func (p Pointer) AppendToken(tok string) Pointer {
132 return Pointer(appendEscapePointerName([]byte(p+"/"), tok))
133 }
134
135 // TODO: Add Pointer.AppendTokens,
136 // but should this take in a ...string or an iter.Seq[string]?
137
138 // Tokens returns an iterator over the reference tokens in the JSON pointer,
139 // starting from the first token until the last token (unless stopped early).
140 func (p Pointer) Tokens() iter.Seq[string] {
141 return func(yield func(string) bool) {
142 for len(p) > 0 {
143 p = Pointer(strings.TrimPrefix(string(p), "/"))
144 i := min(uint(strings.IndexByte(string(p), '/')), uint(len(p)))
145 if !yield(unescapePointerToken(string(p)[:i])) {
146 return
147 }
148 p = p[i:]
149 }
150 }
151 }
152
153 func unescapePointerToken(token string) string {
154 if strings.Contains(token, "~") {
155 // Per RFC 6901, section 3, unescape '~' and '/' characters.
156 token = strings.ReplaceAll(token, "~1", "/")
157 token = strings.ReplaceAll(token, "~0", "~")
158 }
159 return token
160 }
161
162 // appendStackPointer appends a JSON Pointer (RFC 6901) to the current value.
163 //
164 // - If where is -1, then it points to the previously processed token.
165 //
166 // - If where is 0, then it points to the parent JSON object or array,
167 // or an object member if in-between an object member key and value.
168 // This is useful when the position is ambiguous whether
169 // we are interested in the previous or next token, or
170 // when we are uncertain whether the next token
171 // continues or terminates the current object or array.
172 //
173 // - If where is +1, then it points to the next expected value,
174 // assuming that it continues the current JSON object or array.
175 // As a special case, if the next token is a JSON object name,
176 // then it points to the parent JSON object.
177 //
178 // Invariant: Must call s.names.copyQuotedBuffer beforehand.
179 func (s state) appendStackPointer(b []byte, where int) []byte {
180 var objectDepth int
181 for i := 1; i < s.Tokens.Depth(); i++ {
182 e := s.Tokens.index(i)
183 arrayDelta := -1 // by default point to previous array element
184 if isLast := i == s.Tokens.Depth()-1; isLast {
185 switch {
186 case where < 0 && e.Length() == 0 || where == 0 && !e.needObjectValue() || where > 0 && e.NeedObjectName():
187 return b
188 case where > 0 && e.isArray():
189 arrayDelta = 0 // point to next array element
190 }
191 }
192 switch {
193 case e.isObject():
194 b = appendEscapePointerName(append(b, '/'), s.Names.getUnquoted(objectDepth))
195 objectDepth++
196 case e.isArray():
197 b = strconv.AppendUint(append(b, '/'), uint64(e.Length()+int64(arrayDelta)), 10)
198 }
199 }
200 return b
201 }
202
203 func appendEscapePointerName[Bytes ~[]byte | ~string](b []byte, name Bytes) []byte {
204 for _, r := range string(name) {
205 // Per RFC 6901, section 3, escape '~' and '/' characters.
206 switch r {
207 case '~':
208 b = append(b, "~0"...)
209 case '/':
210 b = append(b, "~1"...)
211 default:
212 b = utf8.AppendRune(b, r)
213 }
214 }
215 return b
216 }
217
218 // stateMachine is a push-down automaton that validates whether
219 // a sequence of tokens is valid or not according to the JSON grammar.
220 // It is useful for both encoding and decoding.
221 //
222 // It is a stack where each entry represents a nested JSON object or array.
223 // The stack has a minimum depth of 1 where the first level is a
224 // virtual JSON array to handle a stream of top-level JSON values.
225 // The top-level virtual JSON array is special in that it doesn't require commas
226 // between each JSON value.
227 //
228 // For performance, most methods are carefully written to be inlinable.
229 // The zero value is a valid state machine ready for use.
230 type stateMachine struct {
231 Stack []stateEntry
232 Last stateEntry
233 }
234
235 // reset resets the state machine.
236 // The machine always starts with a minimum depth of 1.
237 func (m *stateMachine) reset() {
238 m.Stack = m.Stack[:0]
239 if cap(m.Stack) > 1<<10 {
240 m.Stack = nil
241 }
242 m.Last = stateTypeArray
243 }
244
245 // Depth is the current nested depth of JSON objects and arrays.
246 // It is one-indexed (i.e., top-level values have a depth of 1).
247 func (m stateMachine) Depth() int {
248 return len(m.Stack) + 1
249 }
250
251 // index returns a reference to the ith entry.
252 // It is only valid until the next push method call.
253 func (m *stateMachine) index(i int) *stateEntry {
254 if i == len(m.Stack) {
255 return &m.Last
256 }
257 return &m.Stack[i]
258 }
259
260 // DepthLength reports the current nested depth and
261 // the length of the last JSON object or array.
262 func (m stateMachine) DepthLength() (int, int64) {
263 return m.Depth(), m.Last.Length()
264 }
265
266 // appendLiteral appends a JSON literal as the next token in the sequence.
267 // If an error is returned, the state is not mutated.
268 func (m *stateMachine) appendLiteral() error {
269 switch {
270 case m.Last.NeedObjectName():
271 return ErrNonStringName
272 case !m.Last.isValidNamespace():
273 return errInvalidNamespace
274 default:
275 m.Last.Increment()
276 return nil
277 }
278 }
279
280 // appendString appends a JSON string as the next token in the sequence.
281 // If an error is returned, the state is not mutated.
282 func (m *stateMachine) appendString() error {
283 switch {
284 case !m.Last.isValidNamespace():
285 return errInvalidNamespace
286 default:
287 m.Last.Increment()
288 return nil
289 }
290 }
291
292 // appendNumber appends a JSON number as the next token in the sequence.
293 // If an error is returned, the state is not mutated.
294 func (m *stateMachine) appendNumber() error {
295 return m.appendLiteral()
296 }
297
298 // pushObject appends a JSON begin object token as next in the sequence.
299 // If an error is returned, the state is not mutated.
300 func (m *stateMachine) pushObject() error {
301 switch {
302 case m.Last.NeedObjectName():
303 return ErrNonStringName
304 case !m.Last.isValidNamespace():
305 return errInvalidNamespace
306 case len(m.Stack) == maxNestingDepth:
307 return errMaxDepth
308 default:
309 m.Last.Increment()
310 m.Stack = append(m.Stack, m.Last)
311 m.Last = stateTypeObject
312 return nil
313 }
314 }
315
316 // popObject appends a JSON end object token as next in the sequence.
317 // If an error is returned, the state is not mutated.
318 func (m *stateMachine) popObject() error {
319 switch {
320 case !m.Last.isObject():
321 return errMismatchDelim
322 case m.Last.needObjectValue():
323 return errMissingValue
324 case !m.Last.isValidNamespace():
325 return errInvalidNamespace
326 default:
327 m.Last = m.Stack[len(m.Stack)-1]
328 m.Stack = m.Stack[:len(m.Stack)-1]
329 return nil
330 }
331 }
332
333 // pushArray appends a JSON begin array token as next in the sequence.
334 // If an error is returned, the state is not mutated.
335 func (m *stateMachine) pushArray() error {
336 switch {
337 case m.Last.NeedObjectName():
338 return ErrNonStringName
339 case !m.Last.isValidNamespace():
340 return errInvalidNamespace
341 case len(m.Stack) == maxNestingDepth:
342 return errMaxDepth
343 default:
344 m.Last.Increment()
345 m.Stack = append(m.Stack, m.Last)
346 m.Last = stateTypeArray
347 return nil
348 }
349 }
350
351 // popArray appends a JSON end array token as next in the sequence.
352 // If an error is returned, the state is not mutated.
353 func (m *stateMachine) popArray() error {
354 switch {
355 case !m.Last.isArray() || len(m.Stack) == 0: // forbid popping top-level virtual JSON array
356 return errMismatchDelim
357 case !m.Last.isValidNamespace():
358 return errInvalidNamespace
359 default:
360 m.Last = m.Stack[len(m.Stack)-1]
361 m.Stack = m.Stack[:len(m.Stack)-1]
362 return nil
363 }
364 }
365
366 // NeedIndent reports whether indent whitespace should be injected.
367 // A zero value means that no whitespace should be injected.
368 // A positive value means '\n', indentPrefix, and (n-1) copies of indentBody
369 // should be appended to the output immediately before the next token.
370 func (m stateMachine) NeedIndent(next Kind) (n int) {
371 willEnd := next == '}' || next == ']'
372 switch {
373 case m.Depth() == 1:
374 return 0 // top-level values are never indented
375 case m.Last.Length() == 0 && willEnd:
376 return 0 // an empty object or array is never indented
377 case m.Last.Length() == 0 || m.Last.needImplicitComma(next):
378 return m.Depth()
379 case willEnd:
380 return m.Depth() - 1
381 default:
382 return 0
383 }
384 }
385
386 // MayAppendDelim appends a colon or comma that may precede the next token.
387 func (m stateMachine) MayAppendDelim(b []byte, next Kind) []byte {
388 switch {
389 case m.Last.needImplicitColon():
390 return append(b, ':')
391 case m.Last.needImplicitComma(next) && len(m.Stack) != 0: // comma not needed for top-level values
392 return append(b, ',')
393 default:
394 return b
395 }
396 }
397
398 // needDelim reports whether a colon or comma token should be implicitly emitted
399 // before the next token of the specified kind.
400 // A zero value means no delimiter should be emitted.
401 func (m stateMachine) needDelim(next Kind) (delim byte) {
402 switch {
403 case m.Last.needImplicitColon():
404 return ':'
405 case m.Last.needImplicitComma(next) && len(m.Stack) != 0: // comma not needed for top-level values
406 return ','
407 default:
408 return 0
409 }
410 }
411
412 // InvalidateDisabledNamespaces marks all disabled namespaces as invalid.
413 //
414 // For efficiency, Marshal and Unmarshal may disable namespaces since there are
415 // more efficient ways to track duplicate names. However, if an error occurs,
416 // the namespaces in Encoder or Decoder will be left in an inconsistent state.
417 // Mark the namespaces as invalid so that future method calls on
418 // Encoder or Decoder will return an error.
419 func (m *stateMachine) InvalidateDisabledNamespaces() {
420 for i := range m.Depth() {
421 e := m.index(i)
422 if !e.isActiveNamespace() {
423 e.invalidateNamespace()
424 }
425 }
426 }
427
428 // stateEntry encodes several artifacts within a single unsigned integer:
429 // - whether this represents a JSON object or array,
430 // - whether this object should check for duplicate names, and
431 // - how many elements are in this JSON object or array.
432 type stateEntry uint64
433
434 const (
435 // The type mask (1 bit) records whether this is a JSON object or array.
436 stateTypeMask stateEntry = 0x8000_0000_0000_0000
437 stateTypeObject stateEntry = 0x8000_0000_0000_0000
438 stateTypeArray stateEntry = 0x0000_0000_0000_0000
439
440 // The name check mask (2 bit) records whether to update
441 // the namespaces for the current JSON object and
442 // whether the namespace is valid.
443 stateNamespaceMask stateEntry = 0x6000_0000_0000_0000
444 stateDisableNamespace stateEntry = 0x4000_0000_0000_0000
445 stateInvalidNamespace stateEntry = 0x2000_0000_0000_0000
446
447 // The count mask (61 bits) records the number of elements.
448 stateCountMask stateEntry = 0x1fff_ffff_ffff_ffff
449 stateCountLSBMask stateEntry = 0x0000_0000_0000_0001
450 stateCountOdd stateEntry = 0x0000_0000_0000_0001
451 stateCountEven stateEntry = 0x0000_0000_0000_0000
452 )
453
454 // Length reports the number of elements in the JSON object or array.
455 // Each name and value in an object entry is treated as a separate element.
456 func (e stateEntry) Length() int64 {
457 return int64(e & stateCountMask)
458 }
459
460 // isObject reports whether this is a JSON object.
461 func (e stateEntry) isObject() bool {
462 return e&stateTypeMask == stateTypeObject
463 }
464
465 // isArray reports whether this is a JSON array.
466 func (e stateEntry) isArray() bool {
467 return e&stateTypeMask == stateTypeArray
468 }
469
470 // NeedObjectName reports whether the next token must be a JSON string,
471 // which is necessary for JSON object names.
472 func (e stateEntry) NeedObjectName() bool {
473 return e&(stateTypeMask|stateCountLSBMask) == stateTypeObject|stateCountEven
474 }
475
476 // needImplicitColon reports whether an colon should occur next,
477 // which always occurs after JSON object names.
478 func (e stateEntry) needImplicitColon() bool {
479 return e.needObjectValue()
480 }
481
482 // needObjectValue reports whether the next token must be a JSON value,
483 // which is necessary after every JSON object name.
484 func (e stateEntry) needObjectValue() bool {
485 return e&(stateTypeMask|stateCountLSBMask) == stateTypeObject|stateCountOdd
486 }
487
488 // needImplicitComma reports whether an comma should occur next,
489 // which always occurs after a value in a JSON object or array
490 // before the next value (or name).
491 func (e stateEntry) needImplicitComma(next Kind) bool {
492 return !e.needObjectValue() && e.Length() > 0 && next != '}' && next != ']'
493 }
494
495 // Increment increments the number of elements for the current object or array.
496 // This assumes that overflow won't practically be an issue since
497 // 1<<bits.OnesCount(stateCountMask) is sufficiently large.
498 func (e *stateEntry) Increment() {
499 (*e)++
500 }
501
502 // decrement decrements the number of elements for the current object or array.
503 // It is the callers responsibility to ensure that e.length > 0.
504 func (e *stateEntry) decrement() {
505 (*e)--
506 }
507
508 // DisableNamespace disables the JSON object namespace such that the
509 // Encoder or Decoder no longer updates the namespace.
510 func (e *stateEntry) DisableNamespace() {
511 *e |= stateDisableNamespace
512 }
513
514 // isActiveNamespace reports whether the JSON object namespace is actively
515 // being updated and used for duplicate name checks.
516 func (e stateEntry) isActiveNamespace() bool {
517 return e&(stateDisableNamespace) == 0
518 }
519
520 // invalidateNamespace marks the JSON object namespace as being invalid.
521 func (e *stateEntry) invalidateNamespace() {
522 *e |= stateInvalidNamespace
523 }
524
525 // isValidNamespace reports whether the JSON object namespace is valid.
526 func (e stateEntry) isValidNamespace() bool {
527 return e&(stateInvalidNamespace) == 0
528 }
529
530 // objectNameStack is a stack of names when descending into a JSON object.
531 // In contrast to objectNamespaceStack, this only has to remember a single name
532 // per JSON object.
533 //
534 // This data structure may contain offsets to encodeBuffer or decodeBuffer.
535 // It violates clean abstraction of layers, but is significantly more efficient.
536 // This ensures that popping and pushing in the common case is a trivial
537 // push/pop of an offset integer.
538 //
539 // The zero value is an empty names stack ready for use.
540 type objectNameStack struct {
541 // offsets is a stack of offsets for each name.
542 // A non-negative offset is the ending offset into the local names buffer.
543 // A negative offset is the bit-wise inverse of a starting offset into
544 // a remote buffer (e.g., encodeBuffer or decodeBuffer).
545 // A math.MinInt offset at the end implies that the last object is empty.
546 // Invariant: Positive offsets always occur before negative offsets.
547 offsets []int
548 // unquotedNames is a back-to-back concatenation of names.
549 unquotedNames []byte
550 }
551
552 func (ns *objectNameStack) reset() {
553 ns.offsets = ns.offsets[:0]
554 ns.unquotedNames = ns.unquotedNames[:0]
555 if cap(ns.offsets) > 1<<6 {
556 ns.offsets = nil // avoid pinning arbitrarily large amounts of memory
557 }
558 if cap(ns.unquotedNames) > 1<<10 {
559 ns.unquotedNames = nil // avoid pinning arbitrarily large amounts of memory
560 }
561 }
562
563 func (ns *objectNameStack) length() int {
564 return len(ns.offsets)
565 }
566
567 // getUnquoted retrieves the ith unquoted name in the stack.
568 // It returns an empty string if the last object is empty.
569 //
570 // Invariant: Must call copyQuotedBuffer beforehand.
571 func (ns *objectNameStack) getUnquoted(i int) []byte {
572 ns.ensureCopiedBuffer()
573 if i == 0 {
574 return ns.unquotedNames[:ns.offsets[0]]
575 } else {
576 return ns.unquotedNames[ns.offsets[i-1]:ns.offsets[i-0]]
577 }
578 }
579
580 // invalidOffset indicates that the last JSON object currently has no name.
581 const invalidOffset = math.MinInt
582
583 // push descends into a nested JSON object.
584 func (ns *objectNameStack) push() {
585 ns.offsets = append(ns.offsets, invalidOffset)
586 }
587
588 // ReplaceLastQuotedOffset replaces the last name with the starting offset
589 // to the quoted name in some remote buffer. All offsets provided must be
590 // relative to the same buffer until copyQuotedBuffer is called.
591 func (ns *objectNameStack) ReplaceLastQuotedOffset(i int) {
592 // Use bit-wise inversion instead of naive multiplication by -1 to avoid
593 // ambiguity regarding zero (which is a valid offset into the names field).
594 // Bit-wise inversion is mathematically equivalent to -i-1,
595 // such that 0 becomes -1, 1 becomes -2, and so forth.
596 // This ensures that remote offsets are always negative.
597 ns.offsets[len(ns.offsets)-1] = ^i
598 }
599
600 // replaceLastUnquotedName replaces the last name with the provided name.
601 //
602 // Invariant: Must call copyQuotedBuffer beforehand.
603 func (ns *objectNameStack) replaceLastUnquotedName(s string) {
604 ns.ensureCopiedBuffer()
605 var startOffset int
606 if len(ns.offsets) > 1 {
607 startOffset = ns.offsets[len(ns.offsets)-2]
608 }
609 ns.unquotedNames = append(ns.unquotedNames[:startOffset], s...)
610 ns.offsets[len(ns.offsets)-1] = len(ns.unquotedNames)
611 }
612
613 // clearLast removes any name in the last JSON object.
614 // It is semantically equivalent to ns.push followed by ns.pop.
615 func (ns *objectNameStack) clearLast() {
616 ns.offsets[len(ns.offsets)-1] = invalidOffset
617 }
618
619 // pop ascends out of a nested JSON object.
620 func (ns *objectNameStack) pop() {
621 ns.offsets = ns.offsets[:len(ns.offsets)-1]
622 }
623
624 // copyQuotedBuffer copies names from the remote buffer into the local names
625 // buffer so that there are no more offset references into the remote buffer.
626 // This allows the remote buffer to change contents without affecting
627 // the names that this data structure is trying to remember.
628 func (ns *objectNameStack) copyQuotedBuffer(b []byte) {
629 // Find the first negative offset.
630 var i int
631 for i = len(ns.offsets) - 1; i >= 0 && ns.offsets[i] < 0; i-- {
632 continue
633 }
634
635 // Copy each name from the remote buffer into the local buffer.
636 for i = i + 1; i < len(ns.offsets); i++ {
637 if i == len(ns.offsets)-1 && ns.offsets[i] == invalidOffset {
638 if i == 0 {
639 ns.offsets[i] = 0
640 } else {
641 ns.offsets[i] = ns.offsets[i-1]
642 }
643 break // last JSON object had a push without any names
644 }
645
646 // As a form of Hyrum proofing, we write an invalid character into the
647 // buffer to make misuse of Decoder.ReadToken more obvious.
648 // We need to undo that mutation here.
649 quotedName := b[^ns.offsets[i]:]
650 if quotedName[0] == invalidateBufferByte {
651 quotedName[0] = '"'
652 }
653
654 // Append the unquoted name to the local buffer.
655 var startOffset int
656 if i > 0 {
657 startOffset = ns.offsets[i-1]
658 }
659 if n := jsonwire.ConsumeSimpleString(quotedName); n > 0 {
660 ns.unquotedNames = append(ns.unquotedNames[:startOffset], quotedName[len(`"`):n-len(`"`)]...)
661 } else {
662 ns.unquotedNames, _ = jsonwire.AppendUnquote(ns.unquotedNames[:startOffset], quotedName)
663 }
664 ns.offsets[i] = len(ns.unquotedNames)
665 }
666 }
667
668 func (ns *objectNameStack) ensureCopiedBuffer() {
669 if len(ns.offsets) > 0 && ns.offsets[len(ns.offsets)-1] < 0 {
670 panic("BUG: copyQuotedBuffer not called beforehand")
671 }
672 }
673
674 // objectNamespaceStack is a stack of object namespaces.
675 // This data structure assists in detecting duplicate names.
676 type objectNamespaceStack []objectNamespace
677
678 // reset resets the object namespace stack.
679 func (nss *objectNamespaceStack) reset() {
680 if cap(*nss) > 1<<10 {
681 *nss = nil
682 }
683 *nss = (*nss)[:0]
684 }
685
686 // push starts a new namespace for a nested JSON object.
687 func (nss *objectNamespaceStack) push() {
688 if cap(*nss) > len(*nss) {
689 *nss = (*nss)[:len(*nss)+1]
690 nss.Last().reset()
691 } else {
692 *nss = append(*nss, objectNamespace{})
693 }
694 }
695
696 // Last returns a pointer to the last JSON object namespace.
697 func (nss objectNamespaceStack) Last() *objectNamespace {
698 return &nss[len(nss)-1]
699 }
700
701 // pop terminates the namespace for a nested JSON object.
702 func (nss *objectNamespaceStack) pop() {
703 *nss = (*nss)[:len(*nss)-1]
704 }
705
706 // objectNamespace is the namespace for a JSON object.
707 // In contrast to objectNameStack, this needs to remember a all names
708 // per JSON object.
709 //
710 // The zero value is an empty namespace ready for use.
711 type objectNamespace struct {
712 // It relies on a linear search over all the names before switching
713 // to use a Go map for direct lookup.
714
715 // endOffsets is a list of offsets to the end of each name in buffers.
716 // The length of offsets is the number of names in the namespace.
717 endOffsets []uint
718 // allUnquotedNames is a back-to-back concatenation of every name in the namespace.
719 allUnquotedNames []byte
720 // mapNames is a Go map containing every name in the namespace.
721 // Only valid if non-nil.
722 mapNames map[string]struct{}
723 }
724
725 // reset resets the namespace to be empty.
726 func (ns *objectNamespace) reset() {
727 ns.endOffsets = ns.endOffsets[:0]
728 ns.allUnquotedNames = ns.allUnquotedNames[:0]
729 ns.mapNames = nil
730 if cap(ns.endOffsets) > 1<<6 {
731 ns.endOffsets = nil // avoid pinning arbitrarily large amounts of memory
732 }
733 if cap(ns.allUnquotedNames) > 1<<10 {
734 ns.allUnquotedNames = nil // avoid pinning arbitrarily large amounts of memory
735 }
736 }
737
738 // length reports the number of names in the namespace.
739 func (ns *objectNamespace) length() int {
740 return len(ns.endOffsets)
741 }
742
743 // getUnquoted retrieves the ith unquoted name in the namespace.
744 func (ns *objectNamespace) getUnquoted(i int) []byte {
745 if i == 0 {
746 return ns.allUnquotedNames[:ns.endOffsets[0]]
747 } else {
748 return ns.allUnquotedNames[ns.endOffsets[i-1]:ns.endOffsets[i-0]]
749 }
750 }
751
752 // lastUnquoted retrieves the last name in the namespace.
753 func (ns *objectNamespace) lastUnquoted() []byte {
754 return ns.getUnquoted(ns.length() - 1)
755 }
756
757 // insertQuoted inserts a name and reports whether it was inserted,
758 // which only occurs if name is not already in the namespace.
759 // The provided name must be a valid JSON string.
760 func (ns *objectNamespace) insertQuoted(name []byte, isVerbatim bool) bool {
761 if isVerbatim {
762 name = name[len(`"`) : len(name)-len(`"`)]
763 }
764 return ns.insert(name, !isVerbatim)
765 }
766 func (ns *objectNamespace) InsertUnquoted(name []byte) bool {
767 return ns.insert(name, false)
768 }
769 func (ns *objectNamespace) insert(name []byte, quoted bool) bool {
770 var allNames []byte
771 if quoted {
772 allNames, _ = jsonwire.AppendUnquote(ns.allUnquotedNames, name)
773 } else {
774 allNames = append(ns.allUnquotedNames, name...)
775 }
776 name = allNames[len(ns.allUnquotedNames):]
777
778 // Switch to a map if the buffer is too large for linear search.
779 // This does not add the current name to the map.
780 if ns.mapNames == nil && (ns.length() > 64 || len(ns.allUnquotedNames) > 1024) {
781 ns.mapNames = make(map[string]struct{})
782 var startOffset uint
783 for _, endOffset := range ns.endOffsets {
784 name := ns.allUnquotedNames[startOffset:endOffset]
785 ns.mapNames[string(name)] = struct{}{} // allocates a new string
786 startOffset = endOffset
787 }
788 }
789
790 if ns.mapNames == nil {
791 // Perform linear search over the buffer to find matching names.
792 // It provides O(n) lookup, but does not require any allocations.
793 var startOffset uint
794 for _, endOffset := range ns.endOffsets {
795 if string(ns.allUnquotedNames[startOffset:endOffset]) == string(name) {
796 return false
797 }
798 startOffset = endOffset
799 }
800 } else {
801 // Use the map if it is populated.
802 // It provides O(1) lookup, but requires a string allocation per name.
803 if _, ok := ns.mapNames[string(name)]; ok {
804 return false
805 }
806 ns.mapNames[string(name)] = struct{}{} // allocates a new string
807 }
808
809 ns.allUnquotedNames = allNames
810 ns.endOffsets = append(ns.endOffsets, uint(len(ns.allUnquotedNames)))
811 return true
812 }
813
814 // removeLast removes the last name in the namespace.
815 func (ns *objectNamespace) removeLast() {
816 if ns.mapNames != nil {
817 delete(ns.mapNames, string(ns.lastUnquoted()))
818 }
819 if ns.length()-1 == 0 {
820 ns.endOffsets = ns.endOffsets[:0]
821 ns.allUnquotedNames = ns.allUnquotedNames[:0]
822 } else {
823 ns.endOffsets = ns.endOffsets[:ns.length()-1]
824 ns.allUnquotedNames = ns.allUnquotedNames[:ns.endOffsets[ns.length()-1]]
825 }
826 }