Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/jsontext/value.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 "io"
11 "slices"
12 "sync"
13
14 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags"
15 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
16 )
17
18 // NOTE: Value is analogous to v1 json.RawMessage.
19
20 // AppendFormat formats the JSON value in src and appends it to dst
21 // according to the specified options.
22 // See [Value.Format] for more details about the formatting behavior.
23 //
24 // The dst and src may overlap.
25 // If an error is reported, then the entirety of src is appended to dst.
26 func AppendFormat(dst, src []byte, opts ...Options) ([]byte, error) {
27 e := getBufferedEncoder(opts...)
28 defer putBufferedEncoder(e)
29 e.s.Flags.Set(jsonflags.OmitTopLevelNewline | 1)
30 if err := e.s.WriteValue(src); err != nil {
31 return append(dst, src...), err
32 }
33 return append(dst, e.s.Buf...), nil
34 }
35
36 // Value represents a single raw JSON value, which may be one of the following:
37 // - a JSON literal (i.e., null, true, or false)
38 // - a JSON string (e.g., "hello, world!")
39 // - a JSON number (e.g., 123.456)
40 // - an entire JSON object (e.g., {"fizz":"buzz"} )
41 // - an entire JSON array (e.g., [1,2,3] )
42 //
43 // Value can represent entire array or object values, while [Token] cannot.
44 // Value may contain leading and/or trailing whitespace.
45 type Value []byte
46
47 // Clone returns a copy of v.
48 func (v Value) Clone() Value {
49 return bytes.Clone(v)
50 }
51
52 // String returns the string formatting of v.
53 func (v Value) String() string {
54 if v == nil {
55 return "null"
56 }
57 return string(v)
58 }
59
60 // IsValid reports whether the raw JSON value is syntactically valid
61 // according to the specified options.
62 //
63 // By default (if no options are specified), it validates according to RFC 7493.
64 // It verifies whether the input is properly encoded as UTF-8,
65 // that escape sequences within strings decode to valid Unicode codepoints, and
66 // that all names in each object are unique.
67 // It does not verify whether numbers are representable within the limits
68 // of any common numeric type (e.g., float64, int64, or uint64).
69 //
70 // Relevant options include:
71 // - [AllowDuplicateNames]
72 // - [AllowInvalidUTF8]
73 //
74 // All other options are ignored.
75 func (v Value) IsValid(opts ...Options) bool {
76 // TODO: Document support for [WithByteLimit] and [WithDepthLimit].
77 d := getBufferedDecoder(v, opts...)
78 defer putBufferedDecoder(d)
79 _, errVal := d.ReadValue()
80 _, errEOF := d.ReadToken()
81 return errVal == nil && errEOF == io.EOF
82 }
83
84 // Format formats the raw JSON value in place.
85 //
86 // By default (if no options are specified), it validates according to RFC 7493
87 // and produces the minimal JSON representation, where
88 // all whitespace is elided and JSON strings use the shortest encoding.
89 //
90 // Relevant options include:
91 // - [AllowDuplicateNames]
92 // - [AllowInvalidUTF8]
93 // - [EscapeForHTML]
94 // - [EscapeForJS]
95 // - [PreserveRawStrings]
96 // - [CanonicalizeRawInts]
97 // - [CanonicalizeRawFloats]
98 // - [ReorderRawObjects]
99 // - [SpaceAfterColon]
100 // - [SpaceAfterComma]
101 // - [Multiline]
102 // - [WithIndent]
103 // - [WithIndentPrefix]
104 //
105 // All other options are ignored.
106 //
107 // It is guaranteed to succeed if the value is valid according to the same options.
108 // If the value is already formatted, then the buffer is not mutated.
109 func (v *Value) Format(opts ...Options) error {
110 // TODO: Document support for [WithByteLimit] and [WithDepthLimit].
111 return v.format(opts, nil)
112 }
113
114 // format accepts two []Options to avoid the allocation appending them together.
115 // It is equivalent to v.Format(append(opts1, opts2...)...).
116 func (v *Value) format(opts1, opts2 []Options) error {
117 e := getBufferedEncoder(opts1...)
118 defer putBufferedEncoder(e)
119 e.s.Join(opts2...)
120 e.s.Flags.Set(jsonflags.OmitTopLevelNewline | 1)
121 if err := e.s.WriteValue(*v); err != nil {
122 return err
123 }
124 if !bytes.Equal(*v, e.s.Buf) {
125 *v = append((*v)[:0], e.s.Buf...)
126 }
127 return nil
128 }
129
130 // Compact removes all whitespace from the raw JSON value.
131 //
132 // It does not reformat JSON strings or numbers to use any other representation.
133 // To maximize the set of JSON values that can be formatted,
134 // this permits values with duplicate names and invalid UTF-8.
135 //
136 // Compact is equivalent to calling [Value.Format] with the following options:
137 // - [AllowDuplicateNames](true)
138 // - [AllowInvalidUTF8](true)
139 // - [PreserveRawStrings](true)
140 //
141 // Any options specified by the caller are applied after the initial set
142 // and may deliberately override prior options.
143 func (v *Value) Compact(opts ...Options) error {
144 return v.format([]Options{
145 AllowDuplicateNames(true),
146 AllowInvalidUTF8(true),
147 PreserveRawStrings(true),
148 }, opts)
149 }
150
151 // Indent reformats the whitespace in the raw JSON value so that each element
152 // in a JSON object or array begins on a indented line according to the nesting.
153 //
154 // It does not reformat JSON strings or numbers to use any other representation.
155 // To maximize the set of JSON values that can be formatted,
156 // this permits values with duplicate names and invalid UTF-8.
157 //
158 // Indent is equivalent to calling [Value.Format] with the following options:
159 // - [AllowDuplicateNames](true)
160 // - [AllowInvalidUTF8](true)
161 // - [PreserveRawStrings](true)
162 // - [Multiline](true)
163 //
164 // Any options specified by the caller are applied after the initial set
165 // and may deliberately override prior options.
166 func (v *Value) Indent(opts ...Options) error {
167 return v.format([]Options{
168 AllowDuplicateNames(true),
169 AllowInvalidUTF8(true),
170 PreserveRawStrings(true),
171 Multiline(true),
172 }, opts)
173 }
174
175 // Canonicalize canonicalizes the raw JSON value according to the
176 // JSON Canonicalization Scheme (JCS) as defined by RFC 8785
177 // where it produces a stable representation of a JSON value.
178 //
179 // JSON strings are formatted to use their minimal representation,
180 // JSON numbers are formatted as double precision numbers according
181 // to some stable serialization algorithm.
182 // JSON object members are sorted in ascending order by name.
183 // All whitespace is removed.
184 //
185 // The output stability is dependent on the stability of the application data
186 // (see RFC 8785, Appendix E). It cannot produce stable output from
187 // fundamentally unstable input. For example, if the JSON value
188 // contains ephemeral data (e.g., a frequently changing timestamp),
189 // then the value is still unstable regardless of whether this is called.
190 //
191 // Canonicalize is equivalent to calling [Value.Format] with the following options:
192 // - [CanonicalizeRawInts](true)
193 // - [CanonicalizeRawFloats](true)
194 // - [ReorderRawObjects](true)
195 //
196 // Any options specified by the caller are applied after the initial set
197 // and may deliberately override prior options.
198 //
199 // Note that JCS treats all JSON numbers as IEEE 754 double precision numbers.
200 // Any numbers with precision beyond what is representable by that form
201 // will lose their precision when canonicalized. For example, integer values
202 // beyond ±2⁵³ will lose their precision. To preserve the original representation
203 // of JSON integers, additionally set [CanonicalizeRawInts] to false:
204 //
205 // v.Canonicalize(jsontext.CanonicalizeRawInts(false))
206 func (v *Value) Canonicalize(opts ...Options) error {
207 return v.format([]Options{
208 CanonicalizeRawInts(true),
209 CanonicalizeRawFloats(true),
210 ReorderRawObjects(true),
211 }, opts)
212 }
213
214 // MarshalJSON returns v as the JSON encoding of v.
215 // It returns the stored value as the raw JSON output without any validation.
216 // If v is nil, then this returns a JSON null.
217 func (v Value) MarshalJSON() ([]byte, error) {
218 // NOTE: This matches the behavior of v1 json.RawMessage.MarshalJSON.
219 if v == nil {
220 return []byte("null"), nil
221 }
222 return v, nil
223 }
224
225 // UnmarshalJSON sets v as the JSON encoding of b.
226 // It stores a copy of the provided raw JSON input without any validation.
227 func (v *Value) UnmarshalJSON(b []byte) error {
228 // NOTE: This matches the behavior of v1 json.RawMessage.UnmarshalJSON.
229 if v == nil {
230 return errors.New("jsontext.Value: UnmarshalJSON on nil pointer")
231 }
232 *v = append((*v)[:0], b...)
233 return nil
234 }
235
236 // Kind returns the starting token kind.
237 // For a valid value, this will never include '}' or ']'.
238 func (v Value) Kind() Kind {
239 if v := v[jsonwire.ConsumeWhitespace(v):]; len(v) > 0 {
240 return Kind(v[0]).normalize()
241 }
242 return invalidKind
243 }
244
245 const commaAndWhitespace = ", \n\r\t"
246
247 type objectMember struct {
248 // name is the unquoted name.
249 name []byte // e.g., "name"
250 // buffer is the entirety of the raw JSON object member
251 // starting from right after the previous member (or opening '{')
252 // until right after the member value.
253 buffer []byte // e.g., `, \n\r\t"name": "value"`
254 }
255
256 func (x objectMember) Compare(y objectMember) int {
257 if c := jsonwire.CompareUTF16(x.name, y.name); c != 0 {
258 return c
259 }
260 // With [AllowDuplicateNames] or [AllowInvalidUTF8],
261 // names could be identical, so also sort using the member value.
262 return jsonwire.CompareUTF16(
263 bytes.TrimLeft(x.buffer, commaAndWhitespace),
264 bytes.TrimLeft(y.buffer, commaAndWhitespace))
265 }
266
267 var objectMemberPool = sync.Pool{New: func() any { return new([]objectMember) }}
268
269 func getObjectMembers() *[]objectMember {
270 ns := objectMemberPool.Get().(*[]objectMember)
271 *ns = (*ns)[:0]
272 return ns
273 }
274 func putObjectMembers(ns *[]objectMember) {
275 if cap(*ns) < 1<<10 {
276 clear(*ns) // avoid pinning name and buffer
277 objectMemberPool.Put(ns)
278 }
279 }
280
281 // mustReorderObjects reorders in-place all object members in a JSON value,
282 // which must be valid otherwise it panics.
283 func mustReorderObjects(b []byte) {
284 // Obtain a buffered encoder just to use its internal buffer as
285 // a scratch buffer for reordering object members.
286 e2 := getBufferedEncoder()
287 defer putBufferedEncoder(e2)
288
289 // Disable unnecessary checks to syntactically parse the JSON value.
290 d := getBufferedDecoder(b)
291 defer putBufferedDecoder(d)
292 d.s.Flags.Set(jsonflags.AllowDuplicateNames | jsonflags.AllowInvalidUTF8 | 1)
293 mustReorderObjectsFromDecoder(d, &e2.s.Buf) // per RFC 8785, section 3.2.3
294 }
295
296 // mustReorderObjectsFromDecoder recursively reorders all object members in place
297 // according to the ordering specified in RFC 8785, section 3.2.3.
298 //
299 // Pre-conditions:
300 // - The value is valid (i.e., no decoder errors should ever occur).
301 // - Initial call is provided a Decoder reading from the start of v.
302 //
303 // Post-conditions:
304 // - Exactly one JSON value is read from the Decoder.
305 // - All fully-parsed JSON objects are reordered by directly moving
306 // the members in the value buffer.
307 //
308 // The runtime is approximately O(n·log(n)) + O(m·log(m)),
309 // where n is len(v) and m is the total number of object members.
310 func mustReorderObjectsFromDecoder(d *Decoder, scratch *[]byte) {
311 switch tok, err := d.ReadToken(); tok.Kind() {
312 case '{':
313 // Iterate and collect the name and offsets for every object member.
314 members := getObjectMembers()
315 defer putObjectMembers(members)
316 var prevMember objectMember
317 isSorted := true
318
319 beforeBody := d.InputOffset() // offset after '{'
320 for d.PeekKind() != '}' {
321 beforeName := d.InputOffset()
322 var flags jsonwire.ValueFlags
323 name, _ := d.s.ReadValue(&flags)
324 name = jsonwire.UnquoteMayCopy(name, flags.IsVerbatim())
325 mustReorderObjectsFromDecoder(d, scratch)
326 afterValue := d.InputOffset()
327
328 currMember := objectMember{name, d.s.buf[beforeName:afterValue]}
329 if isSorted && len(*members) > 0 {
330 isSorted = objectMember.Compare(prevMember, currMember) < 0
331 }
332 *members = append(*members, currMember)
333 prevMember = currMember
334 }
335 afterBody := d.InputOffset() // offset before '}'
336 d.ReadToken()
337
338 // Sort the members; return early if it's already sorted.
339 if isSorted {
340 return
341 }
342 firstBufferBeforeSorting := (*members)[0].buffer
343 slices.SortFunc(*members, objectMember.Compare)
344 firstBufferAfterSorting := (*members)[0].buffer
345
346 // Append the reordered members to a new buffer,
347 // then copy the reordered members back over the original members.
348 // Avoid swapping in place since each member may be a different size
349 // where moving a member over a smaller member may corrupt the data
350 // for subsequent members before they have been moved.
351 //
352 // The following invariant must hold:
353 // sum([m.after-m.before for m in members]) == afterBody-beforeBody
354 commaAndWhitespacePrefix := func(b []byte) []byte {
355 return b[:len(b)-len(bytes.TrimLeft(b, commaAndWhitespace))]
356 }
357 sorted := (*scratch)[:0]
358 for i, member := range *members {
359 switch {
360 case i == 0 && &member.buffer[0] != &firstBufferBeforeSorting[0]:
361 // First member after sorting is not the first member before sorting,
362 // so use the prefix of the first member before sorting.
363 sorted = append(sorted, commaAndWhitespacePrefix(firstBufferBeforeSorting)...)
364 sorted = append(sorted, bytes.TrimLeft(member.buffer, commaAndWhitespace)...)
365 case i != 0 && &member.buffer[0] == &firstBufferBeforeSorting[0]:
366 // Later member after sorting is the first member before sorting,
367 // so use the prefix of the first member after sorting.
368 sorted = append(sorted, commaAndWhitespacePrefix(firstBufferAfterSorting)...)
369 sorted = append(sorted, bytes.TrimLeft(member.buffer, commaAndWhitespace)...)
370 default:
371 sorted = append(sorted, member.buffer...)
372 }
373 }
374 if int(afterBody-beforeBody) != len(sorted) {
375 panic("BUG: length invariant violated")
376 }
377 copy(d.s.buf[beforeBody:afterBody], sorted)
378
379 // Update scratch buffer to the largest amount ever used.
380 if len(sorted) > len(*scratch) {
381 *scratch = sorted
382 }
383 case '[':
384 for d.PeekKind() != ']' {
385 mustReorderObjectsFromDecoder(d, scratch)
386 }
387 d.ReadToken()
388 default:
389 if err != nil {
390 panic("BUG: " + err.Error())
391 }
392 }
393 }