Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/arshal_funcs.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 json
6
7 import (
8 "errors"
9 "fmt"
10 "reflect"
11 "sync"
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/jsontext"
17 )
18
19 // SkipFunc may be returned by [MarshalToFunc] and [UnmarshalFromFunc] functions.
20 //
21 // Any function that returns SkipFunc must not cause observable side effects
22 // on the provided [jsontext.Encoder] or [jsontext.Decoder].
23 // For example, it is permissible to call [jsontext.Decoder.PeekKind],
24 // but not permissible to call [jsontext.Decoder.ReadToken] or
25 // [jsontext.Encoder.WriteToken] since such methods mutate the state.
26 var SkipFunc = errors.New("json: skip function")
27
28 var errSkipMutation = errors.New("must not read or write any tokens when skipping")
29 var errNonSingularValue = errors.New("must read or write exactly one value")
30
31 // Marshalers is a list of functions that may override the marshal behavior
32 // of specific types. Populate [WithMarshalers] to use it with
33 // [Marshal], [MarshalWrite], or [MarshalEncode].
34 // A nil *Marshalers is equivalent to an empty list.
35 // There are no exported fields or methods on Marshalers.
36 type Marshalers = typedMarshalers
37
38 // JoinMarshalers constructs a flattened list of marshal functions.
39 // If multiple functions in the list are applicable for a value of a given type,
40 // then those earlier in the list take precedence over those that come later.
41 // If a function returns [SkipFunc], then the next applicable function is called,
42 // otherwise the default marshaling behavior is used.
43 //
44 // For example:
45 //
46 // m1 := JoinMarshalers(f1, f2)
47 // m2 := JoinMarshalers(f0, m1, f3) // equivalent to m3
48 // m3 := JoinMarshalers(f0, f1, f2, f3) // equivalent to m2
49 func JoinMarshalers(ms ...*Marshalers) *Marshalers {
50 return newMarshalers(ms...)
51 }
52
53 // Unmarshalers is a list of functions that may override the unmarshal behavior
54 // of specific types. Populate [WithUnmarshalers] to use it with
55 // [Unmarshal], [UnmarshalRead], or [UnmarshalDecode].
56 // A nil *Unmarshalers is equivalent to an empty list.
57 // There are no exported fields or methods on Unmarshalers.
58 type Unmarshalers = typedUnmarshalers
59
60 // JoinUnmarshalers constructs a flattened list of unmarshal functions.
61 // If multiple functions in the list are applicable for a value of a given type,
62 // then those earlier in the list take precedence over those that come later.
63 // If a function returns [SkipFunc], then the next applicable function is called,
64 // otherwise the default unmarshaling behavior is used.
65 //
66 // For example:
67 //
68 // u1 := JoinUnmarshalers(f1, f2)
69 // u2 := JoinUnmarshalers(f0, u1, f3) // equivalent to u3
70 // u3 := JoinUnmarshalers(f0, f1, f2, f3) // equivalent to u2
71 func JoinUnmarshalers(us ...*Unmarshalers) *Unmarshalers {
72 return newUnmarshalers(us...)
73 }
74
75 type typedMarshalers = typedArshalers[jsontext.Encoder]
76 type typedUnmarshalers = typedArshalers[jsontext.Decoder]
77 type typedArshalers[Coder any] struct {
78 nonComparable
79
80 fncVals []typedArshaler[Coder]
81 fncCache sync.Map // map[reflect.Type]arshaler
82
83 // fromAny reports whether any of Go types used to represent arbitrary JSON
84 // (i.e., any, bool, string, float64, map[string]any, or []any) matches
85 // any of the provided type-specific arshalers.
86 //
87 // This bit of information is needed in arshal_default.go to determine
88 // whether to use the specialized logic in arshal_any.go to handle
89 // the any interface type. The logic in arshal_any.go does not support
90 // type-specific arshal functions, so we must avoid using that logic
91 // if this is true.
92 fromAny bool
93 }
94 type typedMarshaler = typedArshaler[jsontext.Encoder]
95 type typedUnmarshaler = typedArshaler[jsontext.Decoder]
96 type typedArshaler[Coder any] struct {
97 typ reflect.Type
98 fnc func(*Coder, addressableValue, *jsonopts.Struct) error
99 maySkip bool
100 }
101
102 func newMarshalers(ms ...*Marshalers) *Marshalers { return newTypedArshalers(ms...) }
103 func newUnmarshalers(us ...*Unmarshalers) *Unmarshalers { return newTypedArshalers(us...) }
104 func newTypedArshalers[Coder any](as ...*typedArshalers[Coder]) *typedArshalers[Coder] {
105 var a typedArshalers[Coder]
106 for _, a2 := range as {
107 if a2 != nil {
108 a.fncVals = append(a.fncVals, a2.fncVals...)
109 a.fromAny = a.fromAny || a2.fromAny
110 }
111 }
112 if len(a.fncVals) == 0 {
113 return nil
114 }
115 return &a
116 }
117
118 func (a *typedArshalers[Coder]) lookup(fnc func(*Coder, addressableValue, *jsonopts.Struct) error, t reflect.Type) (func(*Coder, addressableValue, *jsonopts.Struct) error, bool) {
119 if a == nil {
120 return fnc, false
121 }
122 if v, ok := a.fncCache.Load(t); ok {
123 if v == nil {
124 return fnc, false
125 }
126 return v.(func(*Coder, addressableValue, *jsonopts.Struct) error), true
127 }
128
129 // Collect a list of arshalers that can be called for this type.
130 // This list may be longer than 1 since some arshalers can be skipped.
131 var fncs []func(*Coder, addressableValue, *jsonopts.Struct) error
132 for _, fncVal := range a.fncVals {
133 if !castableTo(t, fncVal.typ) {
134 continue
135 }
136 fncs = append(fncs, fncVal.fnc)
137 if !fncVal.maySkip {
138 break // subsequent arshalers will never be called
139 }
140 }
141
142 if len(fncs) == 0 {
143 a.fncCache.Store(t, nil) // nil to indicate that no funcs found
144 return fnc, false
145 }
146
147 // Construct an arshaler that may call every applicable arshaler.
148 fncDefault := fnc
149 fnc = func(c *Coder, v addressableValue, o *jsonopts.Struct) error {
150 for _, fnc := range fncs {
151 if err := fnc(c, v, o); err != SkipFunc {
152 return err // may be nil or non-nil
153 }
154 }
155 return fncDefault(c, v, o)
156 }
157
158 // Use the first stored so duplicate work can be garbage collected.
159 v, _ := a.fncCache.LoadOrStore(t, fnc)
160 return v.(func(*Coder, addressableValue, *jsonopts.Struct) error), true
161 }
162
163 // MarshalFunc constructs a type-specific marshaler that
164 // specifies how to marshal values of type T.
165 // T can be any type except a named pointer.
166 // The function is always provided with a non-nil pointer value
167 // if T is an interface or pointer type.
168 //
169 // The function must marshal exactly one JSON value.
170 // The value of T must not be retained outside the function call.
171 // It may not return [SkipFunc].
172 func MarshalFunc[T any](fn func(T) ([]byte, error)) *Marshalers {
173 t := reflect.TypeFor[T]()
174 assertCastableTo(t, true)
175 typFnc := typedMarshaler{
176 typ: t,
177 fnc: func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
178 val, err := fn(va.castTo(t).Interface().(T))
179 if err != nil {
180 err = wrapSkipFunc(err, "marshal function of type func(T) ([]byte, error)")
181 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
182 return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalFunc") // unlike unmarshal, always wrapped
183 }
184 err = newMarshalErrorBefore(enc, t, err)
185 return collapseSemanticErrors(err)
186 }
187 if err := enc.WriteValue(val); err != nil {
188 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
189 return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalFunc") // unlike unmarshal, always wrapped
190 }
191 if isSyntacticError(err) {
192 err = newMarshalErrorBefore(enc, t, err)
193 }
194 return err
195 }
196 return nil
197 },
198 }
199 return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)}
200 }
201
202 // MarshalToFunc constructs a type-specific marshaler that
203 // specifies how to marshal values of type T.
204 // T can be any type except a named pointer.
205 // The function is always provided with a non-nil pointer value
206 // if T is an interface or pointer type.
207 //
208 // The function must marshal exactly one JSON value by calling write methods
209 // on the provided encoder. It may return [SkipFunc] such that marshaling can
210 // move on to the next marshal function. However, no mutable method calls may
211 // be called on the encoder if [SkipFunc] is returned.
212 // The pointer to [jsontext.Encoder] and the value of T
213 // must not be retained outside the function call.
214 func MarshalToFunc[T any](fn func(*jsontext.Encoder, T) error) *Marshalers {
215 t := reflect.TypeFor[T]()
216 assertCastableTo(t, true)
217 typFnc := typedMarshaler{
218 typ: t,
219 fnc: func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
220 xe := export.Encoder(enc)
221 prevDepth, prevLength := xe.Tokens.DepthLength()
222 xe.Flags.Set(jsonflags.WithinArshalCall | 1)
223 err := fn(enc, va.castTo(t).Interface().(T))
224 xe.Flags.Set(jsonflags.WithinArshalCall | 0)
225 currDepth, currLength := xe.Tokens.DepthLength()
226 if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) {
227 err = errNonSingularValue
228 }
229 if err != nil {
230 if err == SkipFunc {
231 if prevDepth == currDepth && prevLength == currLength {
232 return SkipFunc
233 }
234 err = errSkipMutation
235 }
236 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
237 return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalToFunc") // unlike unmarshal, always wrapped
238 }
239 if !export.IsIOError(err) {
240 err = newSemanticErrorWithPosition(enc, t, prevDepth, prevLength, err)
241 }
242 return err
243 }
244 return nil
245 },
246 maySkip: true,
247 }
248 return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)}
249 }
250
251 // UnmarshalFunc constructs a type-specific unmarshaler that
252 // specifies how to unmarshal values of type T.
253 // T must be an unnamed pointer or an interface type.
254 // The function is always provided with a non-nil pointer value.
255 //
256 // The function must unmarshal exactly one JSON value.
257 // The input []byte must not be mutated.
258 // The input []byte and value T must not be retained outside the function call.
259 // It may not return [SkipFunc].
260 func UnmarshalFunc[T any](fn func([]byte, T) error) *Unmarshalers {
261 t := reflect.TypeFor[T]()
262 assertCastableTo(t, false)
263 typFnc := typedUnmarshaler{
264 typ: t,
265 fnc: func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
266 val, err := dec.ReadValue()
267 if err != nil {
268 return err // must be a syntactic or I/O error
269 }
270 err = fn(val, va.castTo(t).Interface().(T))
271 if err != nil {
272 err = wrapSkipFunc(err, "unmarshal function of type func([]byte, T) error")
273 if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
274 return err // unlike marshal, never wrapped
275 }
276 err = newUnmarshalErrorAfter(dec, t, err)
277 return collapseSemanticErrors(err)
278 }
279 return nil
280 },
281 }
282 return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)}
283 }
284
285 // UnmarshalFromFunc constructs a type-specific unmarshaler that
286 // specifies how to unmarshal values of type T.
287 // T must be an unnamed pointer or an interface type.
288 // The function is always provided with a non-nil pointer value.
289 //
290 // The function must unmarshal exactly one JSON value by calling read methods
291 // on the provided decoder. It may return [SkipFunc] such that unmarshaling can
292 // move on to the next unmarshal function. However, no mutable method calls may
293 // be called on the decoder if [SkipFunc] is returned.
294 // The pointer to [jsontext.Decoder] and the value of T
295 // must not be retained outside the function call.
296 func UnmarshalFromFunc[T any](fn func(*jsontext.Decoder, T) error) *Unmarshalers {
297 t := reflect.TypeFor[T]()
298 assertCastableTo(t, false)
299 typFnc := typedUnmarshaler{
300 typ: t,
301 fnc: func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
302 xd := export.Decoder(dec)
303 prevDepth, prevLength := xd.Tokens.DepthLength()
304 xd.Flags.Set(jsonflags.WithinArshalCall | 1)
305 err := fn(dec, va.castTo(t).Interface().(T))
306 xd.Flags.Set(jsonflags.WithinArshalCall | 0)
307 currDepth, currLength := xd.Tokens.DepthLength()
308 if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) {
309 err = errNonSingularValue
310 }
311 if err != nil {
312 if err == SkipFunc {
313 if prevDepth == currDepth && prevLength == currLength {
314 return SkipFunc
315 }
316 err = errSkipMutation
317 }
318 if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
319 if err2 := xd.SkipUntil(prevDepth, prevLength+1); err2 != nil {
320 return err2
321 }
322 return err // unlike marshal, never wrapped
323 }
324 if !isSyntacticError(err) && !export.IsIOError(err) {
325 err = newSemanticErrorWithPosition(dec, t, prevDepth, prevLength, err)
326 }
327 return err
328 }
329 return nil
330 },
331 maySkip: true,
332 }
333 return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)}
334 }
335
336 // assertCastableTo asserts that "to" is a valid type to be casted to.
337 // These are the Go types that type-specific arshalers may operate upon.
338 //
339 // Let AllTypes be the universal set of all possible Go types.
340 // This function generally asserts that:
341 //
342 // len([from for from in AllTypes if castableTo(from, to)]) > 0
343 //
344 // otherwise it panics.
345 //
346 // As a special-case if marshal is false, then we forbid any non-pointer or
347 // non-interface type since it is almost always a bug trying to unmarshal
348 // into something where the end-user caller did not pass in an addressable value
349 // since they will not observe the mutations.
350 func assertCastableTo(to reflect.Type, marshal bool) {
351 switch to.Kind() {
352 case reflect.Interface:
353 return
354 case reflect.Pointer:
355 // Only allow unnamed pointers to be consistent with the fact that
356 // taking the address of a value produces an unnamed pointer type.
357 if to.Name() == "" {
358 return
359 }
360 default:
361 // Technically, non-pointer types are permissible for unmarshal.
362 // However, they are often a bug since the receiver would be immutable.
363 // Thus, only allow them for marshaling.
364 if marshal {
365 return
366 }
367 }
368 if marshal {
369 panic(fmt.Sprintf("input type %v must be an interface type, an unnamed pointer type, or a non-pointer type", to))
370 } else {
371 panic(fmt.Sprintf("input type %v must be an interface type or an unnamed pointer type", to))
372 }
373 }
374
375 // castableTo checks whether values of type "from" can be casted to type "to".
376 // Nil pointer or interface "from" values are never considered castable.
377 //
378 // This function must be kept in sync with addressableValue.castTo.
379 func castableTo(from, to reflect.Type) bool {
380 switch to.Kind() {
381 case reflect.Interface:
382 // TODO: This breaks when ordinary interfaces can have type sets
383 // since interfaces now exist where only the value form of a type (T)
384 // implements the interface, but not the pointer variant (*T).
385 // See https://go.dev/issue/45346.
386 return reflect.PointerTo(from).Implements(to)
387 case reflect.Pointer:
388 // Common case for unmarshaling.
389 // From must be a concrete or interface type.
390 return reflect.PointerTo(from) == to
391 default:
392 // Common case for marshaling.
393 // From must be a concrete type.
394 return from == to
395 }
396 }
397
398 // castTo casts va to the specified type.
399 // If the type is an interface, then the underlying type will always
400 // be a non-nil pointer to a concrete type.
401 //
402 // Requirement: castableTo(va.Type(), to) must hold.
403 func (va addressableValue) castTo(to reflect.Type) reflect.Value {
404 switch to.Kind() {
405 case reflect.Interface:
406 return va.Addr().Convert(to)
407 case reflect.Pointer:
408 return va.Addr()
409 default:
410 return va.Value
411 }
412 }
413
414 // castableToFromAny reports whether "to" can be casted to from any
415 // of the dynamic types used to represent arbitrary JSON.
416 func castableToFromAny(to reflect.Type) bool {
417 for _, from := range []reflect.Type{anyType, boolType, stringType, float64Type, mapStringAnyType, sliceAnyType} {
418 if castableTo(from, to) {
419 return true
420 }
421 }
422 return false
423 }
424
425 func wrapSkipFunc(err error, what string) error {
426 if err == SkipFunc {
427 return errors.New(what + " cannot be skipped")
428 }
429 return err
430 }