Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/arshal_methods.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 "encoding"
9 "errors"
10 "reflect"
11
12 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal"
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/jsonopts"
15 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
16 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext"
17 )
18
19 var errNonStringValue = errors.New("JSON value must be string type")
20
21 // Interfaces for custom serialization.
22 var (
23 jsonMarshalerType = reflect.TypeFor[Marshaler]()
24 jsonMarshalerToType = reflect.TypeFor[MarshalerTo]()
25 jsonUnmarshalerType = reflect.TypeFor[Unmarshaler]()
26 jsonUnmarshalerFromType = reflect.TypeFor[UnmarshalerFrom]()
27 textAppenderType = reflect.TypeFor[encoding.TextAppender]()
28 textMarshalerType = reflect.TypeFor[encoding.TextMarshaler]()
29 textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]()
30
31 allMarshalerTypes = []reflect.Type{jsonMarshalerToType, jsonMarshalerType, textAppenderType, textMarshalerType}
32 allUnmarshalerTypes = []reflect.Type{jsonUnmarshalerFromType, jsonUnmarshalerType, textUnmarshalerType}
33 allMethodTypes = append(allMarshalerTypes, allUnmarshalerTypes...)
34 )
35
36 // Marshaler is implemented by types that can marshal themselves.
37 // It is recommended that types implement [MarshalerTo] unless the implementation
38 // is trying to avoid a hard dependency on the "jsontext" package.
39 //
40 // It is recommended that implementations return a buffer that is safe
41 // for the caller to retain and potentially mutate.
42 type Marshaler interface {
43 MarshalJSON() ([]byte, error)
44 }
45
46 // MarshalerTo is implemented by types that can marshal themselves.
47 // It is recommended that types implement MarshalerTo instead of [Marshaler]
48 // since this is both more performant and flexible.
49 // If a type implements both Marshaler and MarshalerTo,
50 // then MarshalerTo takes precedence. In such a case, both implementations
51 // should aim to have equivalent behavior for the default marshal options.
52 //
53 // The implementation must write only one JSON value to the Encoder and
54 // must not retain the pointer to [jsontext.Encoder].
55 type MarshalerTo interface {
56 MarshalJSONTo(*jsontext.Encoder) error
57
58 // TODO: Should users call the MarshalEncode function or
59 // should/can they call this method directly? Does it matter?
60 }
61
62 // Unmarshaler is implemented by types that can unmarshal themselves.
63 // It is recommended that types implement [UnmarshalerFrom] unless the implementation
64 // is trying to avoid a hard dependency on the "jsontext" package.
65 //
66 // The input can be assumed to be a valid encoding of a JSON value
67 // if called from unmarshal functionality in this package.
68 // UnmarshalJSON must copy the JSON data if it is retained after returning.
69 // It is recommended that UnmarshalJSON implement merge semantics when
70 // unmarshaling into a pre-populated value.
71 //
72 // Implementations must not retain or mutate the input []byte.
73 type Unmarshaler interface {
74 UnmarshalJSON([]byte) error
75 }
76
77 // UnmarshalerFrom is implemented by types that can unmarshal themselves.
78 // It is recommended that types implement UnmarshalerFrom instead of [Unmarshaler]
79 // since this is both more performant and flexible.
80 // If a type implements both Unmarshaler and UnmarshalerFrom,
81 // then UnmarshalerFrom takes precedence. In such a case, both implementations
82 // should aim to have equivalent behavior for the default unmarshal options.
83 //
84 // The implementation must read only one JSON value from the Decoder.
85 // It is recommended that UnmarshalJSONFrom implement merge semantics when
86 // unmarshaling into a pre-populated value.
87 //
88 // Implementations must not retain the pointer to [jsontext.Decoder].
89 type UnmarshalerFrom interface {
90 UnmarshalJSONFrom(*jsontext.Decoder) error
91
92 // TODO: Should users call the UnmarshalDecode function or
93 // should/can they call this method directly? Does it matter?
94 }
95
96 func makeMethodArshaler(fncs *arshaler, t reflect.Type) *arshaler {
97 // Avoid injecting method arshaler on the pointer or interface version
98 // to avoid ever calling the method on a nil pointer or interface receiver.
99 // Let it be injected on the value receiver (which is always addressable).
100 if t.Kind() == reflect.Pointer || t.Kind() == reflect.Interface {
101 return fncs
102 }
103
104 if needAddr, ok := implements(t, textMarshalerType); ok {
105 fncs.nonDefault = true
106 prevMarshal := fncs.marshal
107 fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
108 if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) &&
109 (needAddr && va.forcedAddr) {
110 return prevMarshal(enc, va, mo)
111 }
112 marshaler := va.Addr().Interface().(encoding.TextMarshaler)
113 if err := export.Encoder(enc).AppendRaw('"', false, func(b []byte) ([]byte, error) {
114 b2, err := marshaler.MarshalText()
115 return append(b, b2...), err
116 }); err != nil {
117 err = wrapSkipFunc(err, "marshal method")
118 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
119 return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalText") // unlike unmarshal, always wrapped
120 }
121 if !isSemanticError(err) && !export.IsIOError(err) {
122 err = newMarshalErrorBefore(enc, t, err)
123 }
124 return err
125 }
126 return nil
127 }
128 }
129
130 if needAddr, ok := implements(t, textAppenderType); ok {
131 fncs.nonDefault = true
132 prevMarshal := fncs.marshal
133 fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) (err error) {
134 if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) &&
135 (needAddr && va.forcedAddr) {
136 return prevMarshal(enc, va, mo)
137 }
138 appender := va.Addr().Interface().(encoding.TextAppender)
139 if err := export.Encoder(enc).AppendRaw('"', false, appender.AppendText); err != nil {
140 err = wrapSkipFunc(err, "append method")
141 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
142 return internal.NewMarshalerError(va.Addr().Interface(), err, "AppendText") // unlike unmarshal, always wrapped
143 }
144 if !isSemanticError(err) && !export.IsIOError(err) {
145 err = newMarshalErrorBefore(enc, t, err)
146 }
147 return err
148 }
149 return nil
150 }
151 }
152
153 if needAddr, ok := implements(t, jsonMarshalerType); ok {
154 fncs.nonDefault = true
155 prevMarshal := fncs.marshal
156 fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
157 if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) &&
158 ((needAddr && va.forcedAddr) || export.Encoder(enc).Tokens.Last.NeedObjectName()) {
159 return prevMarshal(enc, va, mo)
160 }
161 marshaler := va.Addr().Interface().(Marshaler)
162 val, err := marshaler.MarshalJSON()
163 if err != nil {
164 err = wrapSkipFunc(err, "marshal method")
165 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
166 return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalJSON") // unlike unmarshal, always wrapped
167 }
168 err = newMarshalErrorBefore(enc, t, err)
169 return collapseSemanticErrors(err)
170 }
171 if err := enc.WriteValue(val); err != nil {
172 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
173 return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalJSON") // unlike unmarshal, always wrapped
174 }
175 if isSyntacticError(err) {
176 err = newMarshalErrorBefore(enc, t, err)
177 }
178 return err
179 }
180 return nil
181 }
182 }
183
184 if needAddr, ok := implements(t, jsonMarshalerToType); ok {
185 fncs.nonDefault = true
186 prevMarshal := fncs.marshal
187 fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
188 if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) &&
189 ((needAddr && va.forcedAddr) || export.Encoder(enc).Tokens.Last.NeedObjectName()) {
190 return prevMarshal(enc, va, mo)
191 }
192 xe := export.Encoder(enc)
193 prevDepth, prevLength := xe.Tokens.DepthLength()
194 xe.Flags.Set(jsonflags.WithinArshalCall | 1)
195 err := va.Addr().Interface().(MarshalerTo).MarshalJSONTo(enc)
196 xe.Flags.Set(jsonflags.WithinArshalCall | 0)
197 currDepth, currLength := xe.Tokens.DepthLength()
198 if (prevDepth != currDepth || prevLength+1 != currLength) && err == nil {
199 err = errNonSingularValue
200 }
201 if err != nil {
202 err = wrapSkipFunc(err, "marshal method")
203 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
204 return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalJSONTo") // unlike unmarshal, always wrapped
205 }
206 if !export.IsIOError(err) {
207 err = newSemanticErrorWithPosition(enc, t, prevDepth, prevLength, err)
208 }
209 return err
210 }
211 return nil
212 }
213 }
214
215 if _, ok := implements(t, textUnmarshalerType); ok {
216 fncs.nonDefault = true
217 fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
218 xd := export.Decoder(dec)
219 var flags jsonwire.ValueFlags
220 val, err := xd.ReadValue(&flags)
221 if err != nil {
222 return err // must be a syntactic or I/O error
223 }
224 if val.Kind() == 'n' {
225 if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) {
226 va.SetZero()
227 }
228 return nil
229 }
230 if val.Kind() != '"' {
231 return newUnmarshalErrorAfter(dec, t, errNonStringValue)
232 }
233 s := jsonwire.UnquoteMayCopy(val, flags.IsVerbatim())
234 unmarshaler := va.Addr().Interface().(encoding.TextUnmarshaler)
235 if err := unmarshaler.UnmarshalText(s); err != nil {
236 err = wrapSkipFunc(err, "unmarshal method")
237 if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
238 return err // unlike marshal, never wrapped
239 }
240 if !isSemanticError(err) && !isSyntacticError(err) && !export.IsIOError(err) {
241 err = newUnmarshalErrorAfter(dec, t, err)
242 }
243 return err
244 }
245 return nil
246 }
247 }
248
249 if _, ok := implements(t, jsonUnmarshalerType); ok {
250 fncs.nonDefault = true
251 prevUnmarshal := fncs.unmarshal
252 fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
253 if uo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) &&
254 export.Decoder(dec).Tokens.Last.NeedObjectName() {
255 return prevUnmarshal(dec, va, uo)
256 }
257 val, err := dec.ReadValue()
258 if err != nil {
259 return err // must be a syntactic or I/O error
260 }
261 unmarshaler := va.Addr().Interface().(Unmarshaler)
262 if err := unmarshaler.UnmarshalJSON(val); err != nil {
263 err = wrapSkipFunc(err, "unmarshal method")
264 if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
265 return err // unlike marshal, never wrapped
266 }
267 err = newUnmarshalErrorAfter(dec, t, err)
268 return collapseSemanticErrors(err)
269 }
270 return nil
271 }
272 }
273
274 if _, ok := implements(t, jsonUnmarshalerFromType); ok {
275 fncs.nonDefault = true
276 prevUnmarshal := fncs.unmarshal
277 fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
278 if uo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) &&
279 export.Decoder(dec).Tokens.Last.NeedObjectName() {
280 return prevUnmarshal(dec, va, uo)
281 }
282 xd := export.Decoder(dec)
283 prevDepth, prevLength := xd.Tokens.DepthLength()
284 xd.Flags.Set(jsonflags.WithinArshalCall | 1)
285 err := va.Addr().Interface().(UnmarshalerFrom).UnmarshalJSONFrom(dec)
286 xd.Flags.Set(jsonflags.WithinArshalCall | 0)
287 currDepth, currLength := xd.Tokens.DepthLength()
288 if (prevDepth != currDepth || prevLength+1 != currLength) && err == nil {
289 err = errNonSingularValue
290 }
291 if err != nil {
292 err = wrapSkipFunc(err, "unmarshal method")
293 if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
294 if err2 := xd.SkipUntil(prevDepth, prevLength+1); err2 != nil {
295 return err2
296 }
297 return err // unlike marshal, never wrapped
298 }
299 if !isSyntacticError(err) && !export.IsIOError(err) {
300 err = newSemanticErrorWithPosition(dec, t, prevDepth, prevLength, err)
301 }
302 return err
303 }
304 return nil
305 }
306 }
307
308 return fncs
309 }
310
311 // implementsAny is like t.Implements(ifaceType) for a list of interfaces,
312 // but checks whether either t or reflect.PointerTo(t) implements the interface.
313 func implementsAny(t reflect.Type, ifaceTypes ...reflect.Type) bool {
314 for _, ifaceType := range ifaceTypes {
315 if _, ok := implements(t, ifaceType); ok {
316 return true
317 }
318 }
319 return false
320 }
321
322 // implements is like t.Implements(ifaceType) but checks whether
323 // either t or reflect.PointerTo(t) implements the interface.
324 // It also reports whether the value needs to be addressed
325 // in order to satisfy the interface.
326 func implements(t, ifaceType reflect.Type) (needAddr, ok bool) {
327 switch {
328 case t.Implements(ifaceType):
329 return false, true
330 case reflect.PointerTo(t).Implements(ifaceType):
331 return true, true
332 default:
333 return false, false
334 }
335 }