1
2
3
4
5
6
7 package json
8
9 import (
10 "errors"
11 "fmt"
12 "io"
13 "reflect"
14 "sync"
15
16 "encoding/json/internal/jsonflags"
17 "encoding/json/internal/jsonopts"
18 "encoding/json/jsontext"
19 )
20
21 var errUnsupportedMutation = errors.New("unsupported calls must not read or write any tokens")
22 var errNonSingularValue = errors.New("must read or write exactly one value")
23
24
25
26
27
28
29 type Marshalers = typedMarshalers
30
31
32
33
34
35
36
37
38
39
40
41
42
43 func JoinMarshalers(ms ...*Marshalers) *Marshalers {
44 return newMarshalers(ms...)
45 }
46
47
48
49
50
51
52 type Unmarshalers = typedUnmarshalers
53
54
55
56
57
58
59
60
61
62
63
64
65
66 func JoinUnmarshalers(us ...*Unmarshalers) *Unmarshalers {
67 return newUnmarshalers(us...)
68 }
69
70 type typedMarshalers = typedArshalers[jsontext.Encoder, maybeAddressableValue]
71 type typedUnmarshalers = typedArshalers[jsontext.Decoder, alwaysAddressableValue]
72 type typedArshalers[Coder, Value any] struct {
73 nonComparable
74
75 fncVals []typedArshaler[Coder, Value]
76 fncCache sync.Map
77
78
79
80
81
82
83
84
85
86
87 fromAny bool
88 }
89 type typedMarshaler = typedArshaler[jsontext.Encoder, maybeAddressableValue]
90 type typedUnmarshaler = typedArshaler[jsontext.Decoder, alwaysAddressableValue]
91 type typedArshaler[Coder, Value any] struct {
92 typ reflect.Type
93 fnc func(*Coder, Value, *jsonopts.Struct) error
94 maySkip bool
95 }
96
97 func newMarshalers(ms ...*Marshalers) *Marshalers { return newTypedArshalers(ms...) }
98 func newUnmarshalers(us ...*Unmarshalers) *Unmarshalers { return newTypedArshalers(us...) }
99 func newTypedArshalers[Coder, Value any](as ...*typedArshalers[Coder, Value]) *typedArshalers[Coder, Value] {
100 var a typedArshalers[Coder, Value]
101 for _, a2 := range as {
102 if a2 != nil {
103 a.fncVals = append(a.fncVals, a2.fncVals...)
104 a.fromAny = a.fromAny || a2.fromAny
105 }
106 }
107 if len(a.fncVals) == 0 {
108 return nil
109 }
110 return &a
111 }
112
113 func (a *typedArshalers[Coder, Value]) lookup(fnc func(*Coder, Value, *jsonopts.Struct) error, t reflect.Type) (func(*Coder, Value, *jsonopts.Struct) error, bool) {
114 if a == nil {
115 return fnc, false
116 }
117 if v, ok := a.fncCache.Load(t); ok {
118 if v == nil {
119 return fnc, false
120 }
121 return v.(func(*Coder, Value, *jsonopts.Struct) error), true
122 }
123
124
125
126 var fncs []func(*Coder, Value, *jsonopts.Struct) error
127 for _, fncVal := range a.fncVals {
128 if !castableTo(t, fncVal.typ) {
129 continue
130 }
131 fncs = append(fncs, fncVal.fnc)
132 if !fncVal.maySkip {
133 break
134 }
135 }
136
137 if len(fncs) == 0 {
138 a.fncCache.Store(t, nil)
139 return fnc, false
140 }
141
142
143 fncDefault := fnc
144 fnc = func(c *Coder, v Value, o *jsonopts.Struct) error {
145 for _, fnc := range fncs {
146 if err := fnc(c, v, o); !errors.Is(err, errors.ErrUnsupported) {
147 return err
148 }
149 }
150 return fncDefault(c, v, o)
151 }
152
153
154 v, _ := a.fncCache.LoadOrStore(t, fnc)
155 return v.(func(*Coder, Value, *jsonopts.Struct) error), true
156 }
157
158
159
160
161
162
163
164
165
166
167 func MarshalFunc[T any](fn func(T) ([]byte, error)) *Marshalers {
168 t := reflect.TypeFor[T]()
169 assertCastableTo(t, true)
170 typFnc := typedMarshaler{
171 typ: t,
172 fnc: func(enc *jsontext.Encoder, vm maybeAddressableValue, mo *jsonopts.Struct) error {
173 va := vm.ensureAddr()
174 v, _ := reflect.TypeAssert[T](va.castTo(t))
175 val, err := fn(v)
176 if err != nil {
177 err = wrapErrUnsupported(err, "marshal function of type func(T) ([]byte, error)")
178 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
179 return newLegacyMarshalerError(vm, true, err, "MarshalFunc")
180 }
181 err = newMarshalErrorBefore(enc, t, err)
182 return collapseSemanticErrors(err)
183 }
184 if err := enc.WriteValue(val); err != nil {
185 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
186 return newLegacyMarshalerError(vm, true, err, "MarshalFunc")
187 }
188 if isSyntacticError(err) {
189 err = newMarshalErrorBefore(enc, t, err)
190 }
191 return err
192 }
193 return nil
194 },
195 }
196 return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)}
197 }
198
199
200
201
202
203
204
205
206
207
208
209 func MarshalToFunc[T any](fn func(*jsontext.Encoder, T) error) *Marshalers {
210 t := reflect.TypeFor[T]()
211 assertCastableTo(t, true)
212 typFnc := typedMarshaler{
213 typ: t,
214 fnc: func(enc *jsontext.Encoder, vm maybeAddressableValue, mo *jsonopts.Struct) error {
215 va := vm.ensureAddr()
216 xe := export.Encoder(enc)
217 prevDepth, prevLength := xe.Tokens.DepthLength()
218 xe.Flags.Set(jsonflags.WithinArshalCall | 1)
219 v, _ := reflect.TypeAssert[T](va.castTo(t))
220 err := fn(enc, v)
221 xe.Flags.Set(jsonflags.WithinArshalCall | 0)
222 currDepth, currLength := xe.Tokens.DepthLength()
223 if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) {
224 err = errNonSingularValue
225 }
226 if err != nil {
227 if errors.Is(err, errors.ErrUnsupported) {
228 if prevDepth == currDepth && prevLength == currLength {
229 return err
230 }
231 err = errUnsupportedMutation
232 }
233 if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
234 return newLegacyMarshalerError(vm, true, err, "MarshalToFunc")
235 }
236 if !export.IsIOError(err) {
237 err = newSemanticErrorWithPosition(enc, t, prevDepth, prevLength, err)
238 }
239 return err
240 }
241 return nil
242 },
243 maySkip: true,
244 }
245 return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)}
246 }
247
248
249
250
251
252
253
254
255
256 func UnmarshalFunc[T any](fn func([]byte, T) error) *Unmarshalers {
257 t := reflect.TypeFor[T]()
258 assertCastableTo(t, false)
259 typFnc := typedUnmarshaler{
260 typ: t,
261 fnc: func(dec *jsontext.Decoder, va alwaysAddressableValue, uo *jsonopts.Struct) error {
262 val, err := dec.ReadValue()
263 if err != nil {
264 return err
265 }
266 v, _ := reflect.TypeAssert[T](va.castTo(t))
267 err = fn(val, v)
268 if err != nil {
269 err = wrapErrUnsupported(err, "unmarshal function of type func([]byte, T) error")
270 if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
271 return err
272 }
273 err = newUnmarshalErrorAfter(dec, t, err)
274 return collapseSemanticErrors(err)
275 }
276 return nil
277 },
278 }
279 return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)}
280 }
281
282
283
284
285
286
287
288
289
290
291 func UnmarshalFromFunc[T any](fn func(*jsontext.Decoder, T) error) *Unmarshalers {
292 t := reflect.TypeFor[T]()
293 assertCastableTo(t, false)
294 typFnc := typedUnmarshaler{
295 typ: t,
296 fnc: func(dec *jsontext.Decoder, va alwaysAddressableValue, uo *jsonopts.Struct) error {
297 xd := export.Decoder(dec)
298 prevDepth, prevLength := xd.Tokens.DepthLength()
299 if prevDepth == 1 && xd.AtEOF() {
300 return io.EOF
301 }
302 xd.Flags.Set(jsonflags.WithinArshalCall | 1)
303 v, _ := reflect.TypeAssert[T](va.castTo(t))
304 err := fn(dec, v)
305 xd.Flags.Set(jsonflags.WithinArshalCall | 0)
306 currDepth, currLength := xd.Tokens.DepthLength()
307 if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) {
308 err = errNonSingularValue
309 }
310 if err != nil {
311 if errors.Is(err, errors.ErrUnsupported) {
312 if prevDepth == currDepth && prevLength == currLength {
313 return err
314 }
315 err = errUnsupportedMutation
316 }
317 if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
318 if err2 := xd.SkipUntil(prevDepth, prevLength+1); err2 != nil {
319 return err2
320 }
321 return err
322 }
323 if !isSyntacticError(err) && !export.IsIOError(err) {
324 err = newSemanticErrorWithPosition(dec, t, prevDepth, prevLength, err)
325 }
326 return err
327 }
328 return nil
329 },
330 maySkip: true,
331 }
332 return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)}
333 }
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349 func assertCastableTo(to reflect.Type, marshal bool) {
350 switch to.Kind() {
351 case reflect.Interface:
352 return
353 case reflect.Pointer:
354
355
356 if to.Name() == "" {
357 return
358 }
359 default:
360
361
362
363 if marshal {
364 return
365 }
366 }
367 if marshal {
368 panic(fmt.Sprintf("input type %v must be an interface type, an unnamed pointer type, or a non-pointer type", to))
369 } else {
370 panic(fmt.Sprintf("input type %v must be an interface type or an unnamed pointer type", to))
371 }
372 }
373
374
375
376
377
378 func castableTo(from, to reflect.Type) bool {
379 switch to.Kind() {
380 case reflect.Interface:
381
382
383
384
385 return reflect.PointerTo(from).Implements(to)
386 case reflect.Pointer:
387
388
389 return reflect.PointerTo(from) == to
390 default:
391
392
393 return from == to
394 }
395 }
396
397
398
399
400
401
402 func (va alwaysAddressableValue) castTo(to reflect.Type) reflect.Value {
403 switch to.Kind() {
404 case reflect.Interface:
405 return va.Addr().Convert(to)
406 case reflect.Pointer:
407 return va.Addr()
408 default:
409 return va.Value
410 }
411 }
412
413
414
415 func castableToFromAny(to reflect.Type) bool {
416 for _, from := range []reflect.Type{anyType, boolType, stringType, float64Type, mapStringAnyType, sliceAnyType} {
417 if castableTo(from, to) {
418 return true
419 }
420 }
421 return false
422 }
423
View as plain text