Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/jsontext/token.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 "bytes"
9 "errors"
10 "math"
11 "strconv"
12
13 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags"
14 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
15 )
16
17 // NOTE: Token is analogous to v1 json.Token.
18
19 const (
20 maxInt64 = math.MaxInt64
21 minInt64 = math.MinInt64
22 maxUint64 = math.MaxUint64
23 minUint64 = 0 // for consistency and readability purposes
24
25 invalidTokenPanic = "invalid jsontext.Token; it has been voided by a subsequent json.Decoder call"
26 )
27
28 var errInvalidToken = errors.New("invalid jsontext.Token")
29
30 // Token represents a lexical JSON token, which may be one of the following:
31 // - a JSON literal (i.e., null, true, or false)
32 // - a JSON string (e.g., "hello, world!")
33 // - a JSON number (e.g., 123.456)
34 // - a begin or end delimiter for a JSON object (i.e., { or } )
35 // - a begin or end delimiter for a JSON array (i.e., [ or ] )
36 //
37 // A Token cannot represent entire array or object values, while a [Value] can.
38 // There is no Token to represent commas and colons since
39 // these structural tokens can be inferred from the surrounding context.
40 type Token struct {
41 nonComparable
42
43 // Tokens can exist in either a "raw" or an "exact" form.
44 // Tokens produced by the Decoder are in the "raw" form.
45 // Tokens returned by constructors are usually in the "exact" form.
46 // The Encoder accepts Tokens in either the "raw" or "exact" form.
47 //
48 // The following chart shows the possible values for each Token type:
49 // ╔═════════════════╦════════════╤════════════╤════════════╗
50 // ║ Token type ║ raw field │ str field │ num field ║
51 // ╠═════════════════╬════════════╪════════════╪════════════╣
52 // ║ null (raw) ║ "null" │ "" │ 0 ║
53 // ║ false (raw) ║ "false" │ "" │ 0 ║
54 // ║ true (raw) ║ "true" │ "" │ 0 ║
55 // ║ string (raw) ║ non-empty │ "" │ offset ║
56 // ║ string (string) ║ nil │ non-empty │ 0 ║
57 // ║ number (raw) ║ non-empty │ "" │ offset ║
58 // ║ number (float) ║ nil │ "f" │ non-zero ║
59 // ║ number (int64) ║ nil │ "i" │ non-zero ║
60 // ║ number (uint64) ║ nil │ "u" │ non-zero ║
61 // ║ object (delim) ║ "{" or "}" │ "" │ 0 ║
62 // ║ array (delim) ║ "[" or "]" │ "" │ 0 ║
63 // ╚═════════════════╩════════════╧════════════╧════════════╝
64 //
65 // Notes:
66 // - For tokens stored in "raw" form, the num field contains the
67 // absolute offset determined by raw.previousOffsetStart().
68 // The buffer itself is stored in raw.previousBuffer().
69 // - JSON literals and structural characters are always in the "raw" form.
70 // - JSON strings and numbers can be in either "raw" or "exact" forms.
71 // - The exact zero value of JSON strings and numbers in the "exact" forms
72 // have ambiguous representation. Thus, they are always represented
73 // in the "raw" form.
74
75 // raw contains a reference to the raw decode buffer.
76 // If non-nil, then its value takes precedence over str and num.
77 // It is only valid if num == raw.previousOffsetStart().
78 raw *decodeBuffer
79
80 // str is the unescaped JSON string if num is zero.
81 // Otherwise, it is "f", "i", or "u" if num should be interpreted
82 // as a float64, int64, or uint64, respectively.
83 str string
84
85 // num is a float64, int64, or uint64 stored as a uint64 value.
86 // It is non-zero for any JSON number in the "exact" form.
87 num uint64
88 }
89
90 // TODO: Does representing 1-byte delimiters as *decodeBuffer cause performance issues?
91
92 var (
93 Null Token = rawToken("null")
94 False Token = rawToken("false")
95 True Token = rawToken("true")
96
97 BeginObject Token = rawToken("{")
98 EndObject Token = rawToken("}")
99 BeginArray Token = rawToken("[")
100 EndArray Token = rawToken("]")
101
102 zeroString Token = rawToken(`""`)
103 zeroNumber Token = rawToken(`0`)
104
105 nanString Token = String("NaN")
106 pinfString Token = String("Infinity")
107 ninfString Token = String("-Infinity")
108 )
109
110 func rawToken(s string) Token {
111 return Token{raw: &decodeBuffer{buf: []byte(s), prevStart: 0, prevEnd: len(s)}}
112 }
113
114 // Bool constructs a Token representing a JSON boolean.
115 func Bool(b bool) Token {
116 if b {
117 return True
118 }
119 return False
120 }
121
122 // String constructs a Token representing a JSON string.
123 // The provided string should contain valid UTF-8, otherwise invalid characters
124 // may be mangled as the Unicode replacement character.
125 func String(s string) Token {
126 if len(s) == 0 {
127 return zeroString
128 }
129 return Token{str: s}
130 }
131
132 // Float constructs a Token representing a JSON number.
133 // The values NaN, +Inf, and -Inf will be represented
134 // as a JSON string with the values "NaN", "Infinity", and "-Infinity".
135 func Float(n float64) Token {
136 switch {
137 case math.Float64bits(n) == 0:
138 return zeroNumber
139 case math.IsNaN(n):
140 return nanString
141 case math.IsInf(n, +1):
142 return pinfString
143 case math.IsInf(n, -1):
144 return ninfString
145 }
146 return Token{str: "f", num: math.Float64bits(n)}
147 }
148
149 // Int constructs a Token representing a JSON number from an int64.
150 func Int(n int64) Token {
151 if n == 0 {
152 return zeroNumber
153 }
154 return Token{str: "i", num: uint64(n)}
155 }
156
157 // Uint constructs a Token representing a JSON number from a uint64.
158 func Uint(n uint64) Token {
159 if n == 0 {
160 return zeroNumber
161 }
162 return Token{str: "u", num: uint64(n)}
163 }
164
165 // Clone makes a copy of the Token such that its value remains valid
166 // even after a subsequent [Decoder.Read] call.
167 func (t Token) Clone() Token {
168 // TODO: Allow caller to avoid any allocations?
169 if raw := t.raw; raw != nil {
170 // Avoid copying globals.
171 if t.raw.prevStart == 0 {
172 switch t.raw {
173 case Null.raw:
174 return Null
175 case False.raw:
176 return False
177 case True.raw:
178 return True
179 case BeginObject.raw:
180 return BeginObject
181 case EndObject.raw:
182 return EndObject
183 case BeginArray.raw:
184 return BeginArray
185 case EndArray.raw:
186 return EndArray
187 }
188 }
189
190 if uint64(raw.previousOffsetStart()) != t.num {
191 panic(invalidTokenPanic)
192 }
193 buf := bytes.Clone(raw.previousBuffer())
194 return Token{raw: &decodeBuffer{buf: buf, prevStart: 0, prevEnd: len(buf)}}
195 }
196 return t
197 }
198
199 // Bool returns the value for a JSON boolean.
200 // It panics if the token kind is not a JSON boolean.
201 func (t Token) Bool() bool {
202 switch t.raw {
203 case True.raw:
204 return true
205 case False.raw:
206 return false
207 default:
208 panic("invalid JSON token kind: " + t.Kind().String())
209 }
210 }
211
212 // appendString appends a JSON string to dst and returns it.
213 // It panics if t is not a JSON string.
214 func (t Token) appendString(dst []byte, flags *jsonflags.Flags) ([]byte, error) {
215 if raw := t.raw; raw != nil {
216 // Handle raw string value.
217 buf := raw.previousBuffer()
218 if Kind(buf[0]) == '"' {
219 if jsonwire.ConsumeSimpleString(buf) == len(buf) {
220 return append(dst, buf...), nil
221 }
222 dst, _, err := jsonwire.ReformatString(dst, buf, flags)
223 return dst, err
224 }
225 } else if len(t.str) != 0 && t.num == 0 {
226 // Handle exact string value.
227 return jsonwire.AppendQuote(dst, t.str, flags)
228 }
229
230 panic("invalid JSON token kind: " + t.Kind().String())
231 }
232
233 // String returns the unescaped string value for a JSON string.
234 // For other JSON kinds, this returns the raw JSON representation.
235 func (t Token) String() string {
236 // This is inlinable to take advantage of "function outlining".
237 // This avoids an allocation for the string(b) conversion
238 // if the caller does not use the string in an escaping manner.
239 // See https://blog.filippo.io/efficient-go-apis-with-the-inliner/
240 s, b := t.string()
241 if len(b) > 0 {
242 return string(b)
243 }
244 return s
245 }
246 func (t Token) string() (string, []byte) {
247 if raw := t.raw; raw != nil {
248 if uint64(raw.previousOffsetStart()) != t.num {
249 panic(invalidTokenPanic)
250 }
251 buf := raw.previousBuffer()
252 if buf[0] == '"' {
253 // TODO: Preserve ValueFlags in Token?
254 isVerbatim := jsonwire.ConsumeSimpleString(buf) == len(buf)
255 return "", jsonwire.UnquoteMayCopy(buf, isVerbatim)
256 }
257 // Handle tokens that are not JSON strings for fmt.Stringer.
258 return "", buf
259 }
260 if len(t.str) != 0 && t.num == 0 {
261 return t.str, nil
262 }
263 // Handle tokens that are not JSON strings for fmt.Stringer.
264 if t.num > 0 {
265 switch t.str[0] {
266 case 'f':
267 return string(jsonwire.AppendFloat(nil, math.Float64frombits(t.num), 64)), nil
268 case 'i':
269 return strconv.FormatInt(int64(t.num), 10), nil
270 case 'u':
271 return strconv.FormatUint(uint64(t.num), 10), nil
272 }
273 }
274 return "<invalid jsontext.Token>", nil
275 }
276
277 // appendNumber appends a JSON number to dst and returns it.
278 // It panics if t is not a JSON number.
279 func (t Token) appendNumber(dst []byte, flags *jsonflags.Flags) ([]byte, error) {
280 if raw := t.raw; raw != nil {
281 // Handle raw number value.
282 buf := raw.previousBuffer()
283 if Kind(buf[0]).normalize() == '0' {
284 dst, _, err := jsonwire.ReformatNumber(dst, buf, flags)
285 return dst, err
286 }
287 } else if t.num != 0 {
288 // Handle exact number value.
289 switch t.str[0] {
290 case 'f':
291 return jsonwire.AppendFloat(dst, math.Float64frombits(t.num), 64), nil
292 case 'i':
293 return strconv.AppendInt(dst, int64(t.num), 10), nil
294 case 'u':
295 return strconv.AppendUint(dst, uint64(t.num), 10), nil
296 }
297 }
298
299 panic("invalid JSON token kind: " + t.Kind().String())
300 }
301
302 // Float returns the floating-point value for a JSON number.
303 // It returns a NaN, +Inf, or -Inf value for any JSON string
304 // with the values "NaN", "Infinity", or "-Infinity".
305 // It panics for all other cases.
306 func (t Token) Float() float64 {
307 if raw := t.raw; raw != nil {
308 // Handle raw number value.
309 if uint64(raw.previousOffsetStart()) != t.num {
310 panic(invalidTokenPanic)
311 }
312 buf := raw.previousBuffer()
313 if Kind(buf[0]).normalize() == '0' {
314 fv, _ := jsonwire.ParseFloat(buf, 64)
315 return fv
316 }
317 } else if t.num != 0 {
318 // Handle exact number value.
319 switch t.str[0] {
320 case 'f':
321 return math.Float64frombits(t.num)
322 case 'i':
323 return float64(int64(t.num))
324 case 'u':
325 return float64(uint64(t.num))
326 }
327 }
328
329 // Handle string values with "NaN", "Infinity", or "-Infinity".
330 if t.Kind() == '"' {
331 switch t.String() {
332 case "NaN":
333 return math.NaN()
334 case "Infinity":
335 return math.Inf(+1)
336 case "-Infinity":
337 return math.Inf(-1)
338 }
339 }
340
341 panic("invalid JSON token kind: " + t.Kind().String())
342 }
343
344 // Int returns the signed integer value for a JSON number.
345 // The fractional component of any number is ignored (truncation toward zero).
346 // Any number beyond the representation of an int64 will be saturated
347 // to the closest representable value.
348 // It panics if the token kind is not a JSON number.
349 func (t Token) Int() int64 {
350 if raw := t.raw; raw != nil {
351 // Handle raw integer value.
352 if uint64(raw.previousOffsetStart()) != t.num {
353 panic(invalidTokenPanic)
354 }
355 neg := false
356 buf := raw.previousBuffer()
357 if len(buf) > 0 && buf[0] == '-' {
358 neg, buf = true, buf[1:]
359 }
360 if numAbs, ok := jsonwire.ParseUint(buf); ok {
361 if neg {
362 if numAbs > -minInt64 {
363 return minInt64
364 }
365 return -1 * int64(numAbs)
366 } else {
367 if numAbs > +maxInt64 {
368 return maxInt64
369 }
370 return +1 * int64(numAbs)
371 }
372 }
373 } else if t.num != 0 {
374 // Handle exact integer value.
375 switch t.str[0] {
376 case 'i':
377 return int64(t.num)
378 case 'u':
379 if t.num > maxInt64 {
380 return maxInt64
381 }
382 return int64(t.num)
383 }
384 }
385
386 // Handle JSON number that is a floating-point value.
387 if t.Kind() == '0' {
388 switch fv := t.Float(); {
389 case fv >= maxInt64:
390 return maxInt64
391 case fv <= minInt64:
392 return minInt64
393 default:
394 return int64(fv) // truncation toward zero
395 }
396 }
397
398 panic("invalid JSON token kind: " + t.Kind().String())
399 }
400
401 // Uint returns the unsigned integer value for a JSON number.
402 // The fractional component of any number is ignored (truncation toward zero).
403 // Any number beyond the representation of an uint64 will be saturated
404 // to the closest representable value.
405 // It panics if the token kind is not a JSON number.
406 func (t Token) Uint() uint64 {
407 // NOTE: This accessor returns 0 for any negative JSON number,
408 // which might be surprising, but is at least consistent with the behavior
409 // of saturating out-of-bounds numbers to the closest representable number.
410
411 if raw := t.raw; raw != nil {
412 // Handle raw integer value.
413 if uint64(raw.previousOffsetStart()) != t.num {
414 panic(invalidTokenPanic)
415 }
416 neg := false
417 buf := raw.previousBuffer()
418 if len(buf) > 0 && buf[0] == '-' {
419 neg, buf = true, buf[1:]
420 }
421 if num, ok := jsonwire.ParseUint(buf); ok {
422 if neg {
423 return minUint64
424 }
425 return num
426 }
427 } else if t.num != 0 {
428 // Handle exact integer value.
429 switch t.str[0] {
430 case 'u':
431 return t.num
432 case 'i':
433 if int64(t.num) < minUint64 {
434 return minUint64
435 }
436 return uint64(int64(t.num))
437 }
438 }
439
440 // Handle JSON number that is a floating-point value.
441 if t.Kind() == '0' {
442 switch fv := t.Float(); {
443 case fv >= maxUint64:
444 return maxUint64
445 case fv <= minUint64:
446 return minUint64
447 default:
448 return uint64(fv) // truncation toward zero
449 }
450 }
451
452 panic("invalid JSON token kind: " + t.Kind().String())
453 }
454
455 // Kind returns the token kind.
456 func (t Token) Kind() Kind {
457 switch {
458 case t.raw != nil:
459 raw := t.raw
460 if uint64(raw.previousOffsetStart()) != t.num {
461 panic(invalidTokenPanic)
462 }
463 return Kind(t.raw.buf[raw.prevStart]).normalize()
464 case t.num != 0:
465 return '0'
466 case len(t.str) != 0:
467 return '"'
468 default:
469 return invalidKind
470 }
471 }
472
473 // Kind represents each possible JSON token kind with a single byte,
474 // which is conveniently the first byte of that kind's grammar
475 // with the restriction that numbers always be represented with '0':
476 //
477 // - 'n': null
478 // - 'f': false
479 // - 't': true
480 // - '"': string
481 // - '0': number
482 // - '{': object begin
483 // - '}': object end
484 // - '[': array begin
485 // - ']': array end
486 //
487 // An invalid kind is usually represented using 0,
488 // but may be non-zero due to invalid JSON data.
489 type Kind byte
490
491 const invalidKind Kind = 0
492
493 // String prints the kind in a humanly readable fashion.
494 func (k Kind) String() string {
495 switch k {
496 case 'n':
497 return "null"
498 case 'f':
499 return "false"
500 case 't':
501 return "true"
502 case '"':
503 return "string"
504 case '0':
505 return "number"
506 case '{':
507 return "{"
508 case '}':
509 return "}"
510 case '[':
511 return "["
512 case ']':
513 return "]"
514 default:
515 return "<invalid jsontext.Kind: " + jsonwire.QuoteRune(string(k)) + ">"
516 }
517 }
518
519 // normalize coalesces all possible starting characters of a number as just '0'.
520 func (k Kind) normalize() Kind {
521 if k == '-' || ('0' <= k && k <= '9') {
522 return '0'
523 }
524 return k
525 }