Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/arshal_any.go

raw
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package json
6
7 import (
8 "cmp"
9 "math"
10 "reflect"
11 "strconv"
12
13 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal"
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/jsonopts"
16 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
17 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext"
18 )
19
20 // This file contains an optimized marshal and unmarshal implementation
21 // for the any type. This type is often used when the Go program has
22 // no knowledge of the JSON schema. This is a common enough occurrence
23 // to justify the complexity of adding logic for this.
24
25 // marshalValueAny marshals a Go any as a JSON value.
26 // This assumes that there are no special formatting directives
27 // for any possible nested value.
28 func marshalValueAny(enc *jsontext.Encoder, val any, mo *jsonopts.Struct) error {
29 switch val := val.(type) {
30 case nil:
31 return enc.WriteToken(jsontext.Null)
32 case bool:
33 return enc.WriteToken(jsontext.Bool(val))
34 case string:
35 return enc.WriteToken(jsontext.String(val))
36 case float64:
37 if math.IsNaN(val) || math.IsInf(val, 0) {
38 break // use default logic below
39 }
40 return enc.WriteToken(jsontext.Float(val))
41 case map[string]any:
42 return marshalObjectAny(enc, val, mo)
43 case []any:
44 return marshalArrayAny(enc, val, mo)
45 }
46
47 v := newAddressableValue(reflect.TypeOf(val))
48 v.Set(reflect.ValueOf(val))
49 marshal := lookupArshaler(v.Type()).marshal
50 if mo.Marshalers != nil {
51 marshal, _ = mo.Marshalers.(*Marshalers).lookup(marshal, v.Type())
52 }
53 return marshal(enc, v, mo)
54 }
55
56 // unmarshalValueAny unmarshals a JSON value as a Go any.
57 // This assumes that there are no special formatting directives
58 // for any possible nested value.
59 // Duplicate names must be rejected since this does not implement merging.
60 func unmarshalValueAny(dec *jsontext.Decoder, uo *jsonopts.Struct) (any, error) {
61 switch k := dec.PeekKind(); k {
62 case '{':
63 return unmarshalObjectAny(dec, uo)
64 case '[':
65 return unmarshalArrayAny(dec, uo)
66 default:
67 xd := export.Decoder(dec)
68 var flags jsonwire.ValueFlags
69 val, err := xd.ReadValue(&flags)
70 if err != nil {
71 return nil, err
72 }
73 switch val.Kind() {
74 case 'n':
75 return nil, nil
76 case 'f':
77 return false, nil
78 case 't':
79 return true, nil
80 case '"':
81 val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim())
82 if xd.StringCache == nil {
83 xd.StringCache = new(stringCache)
84 }
85 return makeString(xd.StringCache, val), nil
86 case '0':
87 if uo.Flags.Get(jsonflags.UnmarshalAnyWithRawNumber) {
88 return internal.RawNumberOf(val), nil
89 }
90 fv, ok := jsonwire.ParseFloat(val, 64)
91 if !ok {
92 return fv, newUnmarshalErrorAfterWithValue(dec, float64Type, strconv.ErrRange)
93 }
94 return fv, nil
95 default:
96 panic("BUG: invalid kind: " + k.String())
97 }
98 }
99 }
100
101 // marshalObjectAny marshals a Go map[string]any as a JSON object
102 // (or as a JSON null if nil and [jsonflags.FormatNilMapAsNull]).
103 func marshalObjectAny(enc *jsontext.Encoder, obj map[string]any, mo *jsonopts.Struct) error {
104 // Check for cycles.
105 xe := export.Encoder(enc)
106 if xe.Tokens.Depth() > startDetectingCyclesAfter {
107 v := reflect.ValueOf(obj)
108 if err := visitPointer(&xe.SeenPointers, v); err != nil {
109 return newMarshalErrorBefore(enc, mapStringAnyType, err)
110 }
111 defer leavePointer(&xe.SeenPointers, v)
112 }
113
114 // Handle empty maps.
115 if len(obj) == 0 {
116 if mo.Flags.Get(jsonflags.FormatNilMapAsNull) && obj == nil {
117 return enc.WriteToken(jsontext.Null)
118 }
119 // Optimize for marshaling an empty map without any preceding whitespace.
120 if !mo.Flags.Get(jsonflags.AnyWhitespace) && !xe.Tokens.Last.NeedObjectName() {
121 xe.Buf = append(xe.Tokens.MayAppendDelim(xe.Buf, '{'), "{}"...)
122 xe.Tokens.Last.Increment()
123 if xe.NeedFlush() {
124 return xe.Flush()
125 }
126 return nil
127 }
128 }
129
130 if err := enc.WriteToken(jsontext.BeginObject); err != nil {
131 return err
132 }
133 // A Go map guarantees that each entry has a unique key
134 // The only possibility of duplicates is due to invalid UTF-8.
135 if !mo.Flags.Get(jsonflags.AllowInvalidUTF8) {
136 xe.Tokens.Last.DisableNamespace()
137 }
138 if !mo.Flags.Get(jsonflags.Deterministic) || len(obj) <= 1 {
139 for name, val := range obj {
140 if err := enc.WriteToken(jsontext.String(name)); err != nil {
141 return err
142 }
143 if err := marshalValueAny(enc, val, mo); err != nil {
144 return err
145 }
146 }
147 } else {
148 names := getStrings(len(obj))
149 var i int
150 for name := range obj {
151 (*names)[i] = name
152 i++
153 }
154 names.Sort()
155 for _, name := range *names {
156 if err := enc.WriteToken(jsontext.String(name)); err != nil {
157 return err
158 }
159 if err := marshalValueAny(enc, obj[name], mo); err != nil {
160 return err
161 }
162 }
163 putStrings(names)
164 }
165 if err := enc.WriteToken(jsontext.EndObject); err != nil {
166 return err
167 }
168 return nil
169 }
170
171 // unmarshalObjectAny unmarshals a JSON object as a Go map[string]any.
172 // It panics if not decoding a JSON object.
173 func unmarshalObjectAny(dec *jsontext.Decoder, uo *jsonopts.Struct) (map[string]any, error) {
174 switch tok, err := dec.ReadToken(); {
175 case err != nil:
176 return nil, err
177 case tok.Kind() != '{':
178 panic("BUG: invalid kind: " + tok.Kind().String())
179 }
180 obj := make(map[string]any)
181 // A Go map guarantees that each entry has a unique key
182 // The only possibility of duplicates is due to invalid UTF-8.
183 if !uo.Flags.Get(jsonflags.AllowInvalidUTF8) {
184 export.Decoder(dec).Tokens.Last.DisableNamespace()
185 }
186 var errUnmarshal error
187 for dec.PeekKind() != '}' {
188 tok, err := dec.ReadToken()
189 if err != nil {
190 return obj, err
191 }
192 name := tok.String()
193
194 // Manually check for duplicate names.
195 if _, ok := obj[name]; ok {
196 // TODO: Unread the object name.
197 name := export.Decoder(dec).PreviousTokenOrValue()
198 err := newDuplicateNameError(dec.StackPointer(), nil, dec.InputOffset()-len64(name))
199 return obj, err
200 }
201
202 val, err := unmarshalValueAny(dec, uo)
203 obj[name] = val
204 if err != nil {
205 if isFatalError(err, uo.Flags) {
206 return obj, err
207 }
208 errUnmarshal = cmp.Or(err, errUnmarshal)
209 }
210 }
211 if _, err := dec.ReadToken(); err != nil {
212 return obj, err
213 }
214 return obj, errUnmarshal
215 }
216
217 // marshalArrayAny marshals a Go []any as a JSON array
218 // (or as a JSON null if nil and [jsonflags.FormatNilSliceAsNull]).
219 func marshalArrayAny(enc *jsontext.Encoder, arr []any, mo *jsonopts.Struct) error {
220 // Check for cycles.
221 xe := export.Encoder(enc)
222 if xe.Tokens.Depth() > startDetectingCyclesAfter {
223 v := reflect.ValueOf(arr)
224 if err := visitPointer(&xe.SeenPointers, v); err != nil {
225 return newMarshalErrorBefore(enc, sliceAnyType, err)
226 }
227 defer leavePointer(&xe.SeenPointers, v)
228 }
229
230 // Handle empty slices.
231 if len(arr) == 0 {
232 if mo.Flags.Get(jsonflags.FormatNilSliceAsNull) && arr == nil {
233 return enc.WriteToken(jsontext.Null)
234 }
235 // Optimize for marshaling an empty slice without any preceding whitespace.
236 if !mo.Flags.Get(jsonflags.AnyWhitespace) && !xe.Tokens.Last.NeedObjectName() {
237 xe.Buf = append(xe.Tokens.MayAppendDelim(xe.Buf, '['), "[]"...)
238 xe.Tokens.Last.Increment()
239 if xe.NeedFlush() {
240 return xe.Flush()
241 }
242 return nil
243 }
244 }
245
246 if err := enc.WriteToken(jsontext.BeginArray); err != nil {
247 return err
248 }
249 for _, val := range arr {
250 if err := marshalValueAny(enc, val, mo); err != nil {
251 return err
252 }
253 }
254 if err := enc.WriteToken(jsontext.EndArray); err != nil {
255 return err
256 }
257 return nil
258 }
259
260 // unmarshalArrayAny unmarshals a JSON array as a Go []any.
261 // It panics if not decoding a JSON array.
262 func unmarshalArrayAny(dec *jsontext.Decoder, uo *jsonopts.Struct) ([]any, error) {
263 switch tok, err := dec.ReadToken(); {
264 case err != nil:
265 return nil, err
266 case tok.Kind() != '[':
267 panic("BUG: invalid kind: " + tok.Kind().String())
268 }
269 arr := []any{}
270 var errUnmarshal error
271 for dec.PeekKind() != ']' {
272 val, err := unmarshalValueAny(dec, uo)
273 arr = append(arr, val)
274 if err != nil {
275 if isFatalError(err, uo.Flags) {
276 return arr, err
277 }
278 errUnmarshal = cmp.Or(errUnmarshal, err)
279 }
280 }
281 if _, err := dec.ReadToken(); err != nil {
282 return arr, err
283 }
284 return arr, errUnmarshal
285 }