Debian Codegraph @

decoder.go

raw
1 // Copyright 2012 The Gorilla 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 schema
6
7 import (
8 "encoding"
9 "errors"
10 "fmt"
11 "maps"
12 "mime/multipart"
13 "reflect"
14 "strconv"
15 "strings"
16 "sync"
17 "unsafe"
18
19 utils "github.com/gofiber/utils/v2"
20 )
21
22 const (
23 defaultMaxSize = 16000
24 )
25
26 // errNotPointerToStruct is returned by Decode for invalid destinations;
27 // hoisted so the check does not allocate on every call.
28 var errNotPointerToStruct = errors.New("schema: interface must be a pointer to struct")
29
30 // fileKeyValues stands in for the value of a multipart file's key in the
31 // decode view. Nothing writes through a source map's values and the map it
32 // goes into is this package's own copy, so one slice serves every file key.
33 var fileKeyValues = []string{""}
34
35 var decodeValueBufferPool = sync.Pool{
36 New: func() any {
37 buf := make([]reflect.Value, 0, 8)
38 return &buf
39 },
40 }
41
42 // NewDecoder returns a new Decoder.
43 func NewDecoder() *Decoder {
44 return &Decoder{cache: newCache(), maxSize: defaultMaxSize}
45 }
46
47 // Decoder decodes values from a map[string][]string to a struct.
48 type Decoder struct {
49 cache *cache
50 zeroEmpty bool
51 ignoreUnknownKeys bool
52 maxSize int
53 }
54
55 // SetAliasTag changes the tag used to locate custom field aliases.
56 // The default tag is "schema".
57 func (d *Decoder) SetAliasTag(tag string) {
58 d.cache.l.Lock()
59 d.cache.tag = tag
60 d.cache.reset()
61 d.cache.l.Unlock()
62 }
63
64 // ZeroEmpty controls the behaviour when the decoder encounters empty values
65 // in a map.
66 // If z is true and a key in the map has the empty string as a value
67 // then the corresponding struct field is set to the zero value.
68 // If z is false then empty strings are ignored.
69 //
70 // The default value is false, that is empty values do not change
71 // the value of the struct field.
72 func (d *Decoder) ZeroEmpty(z bool) {
73 d.zeroEmpty = z
74 }
75
76 // IgnoreUnknownKeys controls the behaviour when the decoder encounters unknown
77 // keys in the map.
78 // If i is true and an unknown field is encountered, it is ignored. This is
79 // similar to how unknown keys are handled by encoding/json.
80 // If i is false then Decode will return an error. Note that any valid keys
81 // will still be decoded in to the target struct.
82 //
83 // To preserve backwards compatibility, the default value is false.
84 func (d *Decoder) IgnoreUnknownKeys(i bool) {
85 d.ignoreUnknownKeys = i
86 }
87
88 // MaxSize limits the size of slices for URL nested arrays or object arrays.
89 // Choose MaxSize carefully; large values may create many zero-value slice elements.
90 // Example: "items.100000=apple" would create a slice with 100,000 empty strings.
91 func (d *Decoder) MaxSize(size int) {
92 d.maxSize = size
93 }
94
95 // RegisterConverter registers a converter function for a custom type.
96 func (d *Decoder) RegisterConverter(value interface{}, converterFunc Converter) {
97 d.cache.registerConverter(value, converterFunc)
98 }
99
100 // Decode decodes a map[string][]string to a struct.
101 //
102 // The first parameter must be a pointer to a struct.
103 //
104 // The second parameter is a map, typically url.Values from an HTTP request.
105 // Keys are "paths" in dotted notation to the struct fields and nested structs.
106 //
107 // See the package documentation for a full explanation of the mechanics.
108 func (d *Decoder) Decode(dst interface{}, src map[string][]string, files ...map[string][]*multipart.FileHeader) error {
109 var multipartFiles map[string][]*multipart.FileHeader
110
111 if len(files) > 0 {
112 multipartFiles = files[0]
113 }
114
115 // Add files as empty string values to the decode view so path parsing
116 // works uniformly. Work on a copy: the caller's src map must not be
117 // mutated (and a caller-provided value under a file's key must not be
118 // overwritten in it).
119 if len(multipartFiles) > 0 {
120 merged := make(map[string][]string, len(src)+len(multipartFiles))
121 maps.Copy(merged, src)
122 for path := range multipartFiles {
123 merged[path] = fileKeyValues
124 }
125 src = merged
126 }
127
128 s := source{m: src}
129 return d.decodeSource(dst, &s, multipartFiles)
130 }
131
132 // DecodeValues decodes key/value pairs to a struct as Decode decodes the map
133 // they make: values[i] is a value of the key keys[i], and a key given more
134 // than once has all of its values, in the order given. It saves a caller that
135 // has the pairs one at a time, as a parsed query string does, building that
136 // map, and saves the decode iterating it.
137 //
138 // Where several keys name the same field, as keys that differ only in case
139 // do, the keys decode in the order of their first pairs, so the key given
140 // first the latest wins; Decode lets whichever its map yields last win.
141 //
142 // The first parameter must be a pointer to a struct, and keys and values must
143 // be the same length. The slices are only read, and only during the call.
144 func (d *Decoder) DecodeValues(dst interface{}, keys, values []string) error {
145 if len(keys) != len(values) {
146 return errValuesLength
147 }
148 // The index is set up field by field where it lies. Go puts a literal for
149 // a variable whose address is taken, or a call's result, together
150 // elsewhere and copies it over, and the copy reads back in wide loads the
151 // words just stored in narrow ones, which stalls each load.
152 var p pairIndex
153 p.keys, p.values = keys, values
154 if n := len(keys); n <= maxScanPairs {
155 var next, last [maxScanPairs]int32
156 p.next, p.last = next[:n], last[:n]
157 } else if n <= maxInlinePairs {
158 var table [2 * maxInlinePairs]int32
159 var next, last [maxInlinePairs]int32
160 p.table, p.next, p.last = table[:indexSize(n)], next[:n], last[:n]
161 } else {
162 p.table, p.next, p.last = make([]int32, indexSize(n)), make([]int32, n), make([]int32, n)
163 }
164 p.index()
165 s := source{pairs: &p}
166 return d.decodeSource(dst, &s, nil)
167 }
168
169 // decodeSource decodes src into dst, the pointer to a struct Decode and
170 // DecodeValues were given, with the files Decode was.
171 func (d *Decoder) decodeSource(dst interface{}, src *source, multipartFiles map[string][]*multipart.FileHeader) (err error) {
172 v := reflect.ValueOf(dst)
173 if v.Kind() != reflect.Pointer || v.Elem().Kind() != reflect.Struct {
174 return errNotPointerToStruct
175 }
176
177 // Catch panics from the decoder and return them as an error.
178 // This is needed because the decoder calls reflect and reflect panics.
179 // Installed before any other work so nothing can crash the caller.
180 defer func() {
181 if r := recover(); r != nil {
182 if e, ok := r.(error); ok {
183 err = e
184 } else {
185 err = fmt.Errorf("schema: panic while decoding: %v", r)
186 }
187 }
188 }()
189
190 v = v.Elem()
191 t := v.Type()
192 rootInfo := d.cache.get(t)
193 // Required-key bookkeeping rides along with the loop below so src is
194 // walked once: the direct lookups settle almost every group here, and
195 // the rest are answered by the nested keys the loop visits anyway.
196 var satisfied []uint64
197 pending := 0
198 if len(rootInfo.requiredGroups) > 0 {
199 // Declared here so a struct with no required keys never pays to
200 // zero it.
201 var requiredBits [requiredBitWords]uint64
202 satisfied, pending = markProvidedDirectly(rootInfo.requiredGroups, src, requiredBits[:])
203 }
204 // Only a struct whose paths carry an index can grow anything.
205 var grow *growTracker
206 if rootInfo.hasIndexedSlice {
207 var tracker growTracker
208 grow = &tracker
209 }
210 // The state decodeKey carries from key to key is kept in variables of
211 // its own rather than a struct: the compiler would let the stack values
212 // above escape along with the errors a struct holding both returns.
213 var errs MultiError
214 if p := src.pairs; p != nil {
215 // A key whose pairs are not adjacent gathers its values here.
216 var scratch [8]string
217 for i, path := range p.keys {
218 if p.first(i) {
219 errs, pending = d.decodeKey(v, rootInfo, multipartFiles, grow, satisfied, path, p.group(i, scratch[:0]), errs, pending)
220 }
221 }
222 } else {
223 for path, values := range src.m {
224 errs, pending = d.decodeKey(v, rootInfo, multipartFiles, grow, satisfied, path, values, errs, pending)
225 }
226 }
227 if rootInfo.needsDefaultsWalk {
228 errs = mergeErrors(errs, d.setDefaults(t, v, src, ""))
229 }
230 errs = mergeErrors(errs, missingRequired(rootInfo.requiredGroups, satisfied, pending))
231 if len(errs) > 0 {
232 return errs
233 }
234 return nil
235 }
236
237 // decodeKey decodes the values of one source key into v, the struct whose
238 // metadata is rootInfo, and returns errs with any error it met added, and
239 // pending less the required groups the key settles in satisfied.
240 func (d *Decoder) decodeKey(
241 v reflect.Value, rootInfo *structInfo, files map[string][]*multipart.FileHeader, grow *growTracker,
242 satisfied []uint64, path string, values []string, errs MultiError, pending int,
243 ) (MultiError, int) {
244 if pending > 0 {
245 if i := strings.IndexByte(path, '.'); i >= 0 && len(values) > 0 {
246 pending = markProvidedByNestedKey(rootInfo, path, i+1, values, satisfied, pending)
247 }
248 }
249 if parts, err := d.cache.parsePathInfo(path, rootInfo); err == nil {
250 var filesSlice []*multipart.FileHeader
251 if files != nil {
252 filesSlice = files[path]
253 }
254 if err = d.decode(v, path, parts, values, filesSlice, grow); err != nil {
255 errs = appendError(errs, path, err)
256 }
257 // A key that names no field is by far the most common failure,
258 // and parsePathInfo returns that sentinel unwrapped, so the
259 // pointer compare keeps errors.Is off the per-key path.
260 } else if err != errInvalidPath && errors.Is(err, errIndexTooLarge) { //nolint:errorlint // see above
261 errs = appendError(errs, path, err)
262 } else if !d.ignoreUnknownKeys {
263 errs = appendError(errs, path, UnknownKeyError{Key: path})
264 }
265 return errs, pending
266 }
267
268 // setDefaults sets the default values when the `default` tag is specified,
269 // default is supported on basic/primitive types and their pointers,
270 // nested structs can also have default tags
271 var (
272 errUnsupportedDefault = errors.New("default option is supported only on: bool, float variants, string, unit variants types or their corresponding pointers or slices")
273 errRequiredDefault = errors.New("required fields cannot have a default value")
274 )
275
276 // resolveDefault converts the field's default option once, when the struct
277 // metadata is built, so setDefaults assigns a resolved value on every call
278 // instead of converting the string each time. Slice and pointer defaults are
279 // still instantiated per call, so no two decoded values share one.
280 func (f *fieldInfo) resolveDefault() {
281 if f.defaultValue == "" {
282 return
283 }
284 def := &fieldDefault{}
285 f.def = def
286 switch f.typ.Kind() {
287 case reflect.Slice:
288 elemT := f.typ.Elem()
289 conv := getBuiltinConverter(elemT.Kind())
290 if conv == nil {
291 return
292 }
293 tmpl := reflect.MakeSlice(f.typ, 0, strings.Count(f.defaultValue, "|")+1)
294 for val := range strings.SplitSeq(f.defaultValue, "|") {
295 v := conv(val)
296 if !v.IsValid() {
297 def.err = fmt.Errorf("failed setting default: %s is not compatible with field %s type", val, f.name)
298 break
299 }
300 // Builtin converters return the underlying kind; convert to the
301 // (possibly named) element type, else Append panics for []MyInt.
302 tmpl = reflect.Append(tmpl, v.Convert(elemT))
303 }
304 def.slice = tmpl
305 case reflect.Ptr:
306 t1 := f.typ.Elem()
307 if conv := getBuiltinConverter(t1.Kind()); conv != nil {
308 if v := conv(f.defaultValue); v.IsValid() {
309 def.val = v.Convert(t1)
310 }
311 }
312 default:
313 if conv := getBuiltinConverter(f.typ.Kind()); conv != nil {
314 if v := conv(f.defaultValue); v.IsValid() {
315 def.val = v.Convert(f.typ)
316 }
317 }
318 }
319 }
320
321 func (d *Decoder) setDefaults(t reflect.Type, v reflect.Value, src *source, prefix string) MultiError {
322 struc := d.cache.get(t)
323 // Skip the walk entirely when it can have no effect (no default tags and
324 // no anonymous embedded pointers to allocate anywhere in the tree) — the
325 // overwhelmingly common case.
326 if !struc.needsDefaultsWalk {
327 return nil
328 }
329
330 var errs MultiError
331
332 // Allocate nil anonymous embedded pointer fields so their promoted
333 // fields stay reachable.
334 for _, idx := range struc.anonymousPtrFields {
335 if field := v.Field(idx); field.IsNil() {
336 field.Set(reflect.New(field.Type().Elem()))
337 }
338 }
339
340 for _, f := range struc.defaultFields {
341 vCurrent := walkIndexChain(v, f.index)
342 if !vCurrent.IsValid() {
343 // Unreachable behind an unsettable nil embedded pointer.
344 continue
345 }
346
347 // vCurrent's type is f.typ; a nested struct is walked under its own
348 // prefix (an empty prefix concatenates without allocating).
349 kind := f.typ.Kind()
350 if kind == reflect.Struct && f.defaultValue == "" {
351 errs = mergeErrors(errs, d.setDefaults(f.typ, vCurrent, src, prefix+f.canonicalDot))
352 } else if kind == reflect.Ptr && f.defaultValue == "" && isPointerToStruct(vCurrent) {
353 errs = mergeErrors(errs, d.setDefaults(f.typ.Elem(), vCurrent.Elem(), src, prefix+f.canonicalDot))
354 }
355
356 def := f.def
357 if def == nil {
358 continue
359 }
360 if f.isRequired {
361 errs = appendError(errs, "default-"+f.name, errRequiredDefault)
362 continue
363 }
364 if !vCurrent.IsZero() || fieldProvided(src, prefix, f) {
365 continue
366 }
367 // The default itself was resolved when the metadata was built; see
368 // resolveDefault. Only the per-call parts remain: the errors a kind
369 // that takes no default reports, and a fresh pointer or slice so no
370 // two decoded values share one.
371 switch kind {
372 case reflect.Struct:
373 errs = appendError(errs, "default-"+f.name, errUnsupportedDefault)
374 case reflect.Slice:
375 if !def.slice.IsValid() {
376 errs = appendError(errs, "default-"+f.name, errUnsupportedDefault)
377 continue
378 }
379 if def.err != nil {
380 errs = appendError(errs, "default-"+f.name, def.err)
381 }
382 fresh := reflect.MakeSlice(f.typ, def.slice.Len(), def.slice.Cap())
383 reflect.Copy(fresh, def.slice)
384 vCurrent.Set(fresh)
385 case reflect.Ptr:
386 t1 := f.typ.Elem()
387 if t1.Kind() == reflect.Struct || t1.Kind() == reflect.Slice {
388 errs = appendError(errs, "default-"+f.name, errUnsupportedDefault)
389 }
390 if def.val.IsValid() {
391 // *elem is assignable to the field even when the field's
392 // type is itself a named pointer type (type MyIntPtr *MyInt),
393 // where converting a *int directly would panic.
394 p := reflect.New(t1)
395 p.Elem().Set(def.val)
396 vCurrent.Set(p)
397 }
398 default:
399 if getBuiltinConverter(kind) == nil {
400 errs = appendError(errs, "default-"+f.name, errUnsupportedDefault)
401 } else if def.val.IsValid() {
402 vCurrent.Set(def.val)
403 }
404 }
405 }
406
407 return errs
408 }
409
410 // growCap is the capacity to give a slice being grown to n elements: room for
411 // another doubling when the slice is tracked, so later indices mostly land
412 // inside it, and exactly n when it is not, since the extra would go unused.
413 func (d *Decoder) growCap(n int, tracked bool) int {
414 if !tracked {
415 return n
416 }
417 c := 2 * n
418 if c < n || c > d.maxSize+1 { // overflow, or past what maxSize admits
419 c = d.maxSize + 1
420 }
421 if c < n {
422 c = n
423 }
424 return c
425 }
426
427 func isPointerToStruct(v reflect.Value) bool {
428 return !v.IsZero() && v.Type().Kind() == reflect.Ptr && v.Elem().Type().Kind() == reflect.Struct
429 }
430
431 func fieldProvided(src *source, prefix string, f *fieldInfo) bool {
432 if keyProvided(src, prefix, f.alias) {
433 return true
434 }
435 return f.alias != f.canonicalAlias && keyProvided(src, prefix, f.canonicalAlias)
436 }
437
438 // keyProvided reports whether prefix+name is a key of src, assembling the key
439 // in a stack buffer when it fits so the probe allocates nothing.
440 func keyProvided(src *source, prefix, name string) bool {
441 if prefix == "" {
442 _, ok := src.lookup(name)
443 return ok
444 }
445 if n := len(prefix) + len(name); n <= maxDirectKeyLen {
446 var buf [maxDirectKeyLen]byte
447 copy(buf[copy(buf[:], prefix):], name)
448 return src.hasBytes(buf[:n])
449 }
450 _, ok := src.lookup(prefix + name)
451 return ok
452 }
453
454 // The set of required fields (including those of nested structs) is
455 // precomputed once per struct type in structInfo.requiredGroups, so what
456 // follows only performs the per-request emptiness checks against src.
457 //
458 // A group is satisfied by a value under one of its own paths, or by any
459 // nested key below one of them ("d.e" satisfies required "d"). Direct paths
460 // are looked up first, since they settle almost every group; what is left is
461 // answered by walking the dotted prefixes of each source key. Decode runs
462 // those three steps around its own loop over src; checkRequired composes them
463 // for a standalone check.
464
465 // requiredBitWords sizes the inline satisfied-group bitset: 256 required
466 // keys, past which it is allocated.
467 const requiredBitWords = 4
468
469 // markProvidedDirectly marks every required group src answers through one of
470 // its own paths, returning the bitset — backed by inline when the groups fit
471 // — and how many are still pending.
472 func markProvidedDirectly(groups []requiredGroup, src *source, inline []uint64) ([]uint64, int) {
473 if len(groups) == 0 {
474 return nil, 0
475 }
476 var satisfied []uint64
477 if w := (len(groups) + 63) >> 6; w <= len(inline) {
478 satisfied = inline[:w]
479 } else {
480 satisfied = make([]uint64, w)
481 }
482 pending := len(groups)
483 for gi := range groups {
484 if directlyProvided(groups[gi].fields, src) {
485 satisfied[gi>>6] |= 1 << uint(gi&63)
486 pending--
487 }
488 }
489 return satisfied, pending
490 }
491
492 // markProvidedByNestedKey walks the dotted prefixes of key from off, marking
493 // every required group they name that val is non-empty for, and returns the
494 // new pending count. Callers test for a dotted, non-empty key themselves, so
495 // the keys that can answer nothing do not pay for a call.
496 func markProvidedByNestedKey(info *structInfo, key string, off int, val []string, satisfied []uint64, pending int) int {
497 for {
498 for _, p := range info.requiredPrefixes[key[:off]] {
499 if satisfied[p.group>>6]&(1<<uint(p.group&63)) != 0 {
500 continue
501 }
502 if !isEmpty(p.typ, val) {
503 satisfied[p.group>>6] |= 1 << uint(p.group&63)
504 pending--
505 }
506 }
507 i := strings.IndexByte(key[off:], '.')
508 if i < 0 {
509 return pending
510 }
511 off += i + 1
512 }
513 }
514
515 // missingRequired reports the required keys nothing in src answered.
516 func missingRequired(groups []requiredGroup, satisfied []uint64, pending int) MultiError {
517 if pending == 0 {
518 return nil
519 }
520 var errs MultiError
521 for gi := range groups {
522 if satisfied[gi>>6]&(1<<uint(gi&63)) == 0 {
523 errs = appendError(errs, groups[gi].key, EmptyFieldError{Key: groups[gi].key})
524 }
525 }
526 return errs
527 }
528
529 // checkRequired reports which of info's required keys src leaves empty: the
530 // standalone form of what Decode folds into its own loop.
531 func (d *Decoder) checkRequired(info *structInfo, src map[string][]string) MultiError {
532 var inline [requiredBitWords]uint64
533 s := source{m: src}
534 satisfied, pending := markProvidedDirectly(info.requiredGroups, &s, inline[:])
535 if pending > 0 {
536 for key, val := range src {
537 i := strings.IndexByte(key, '.')
538 if i < 0 || len(val) == 0 {
539 continue
540 }
541 if pending = markProvidedByNestedKey(info, key, i+1, val, satisfied, pending); pending == 0 {
542 break
543 }
544 }
545 }
546 return missingRequired(info.requiredGroups, satisfied, pending)
547 }
548
549 // requiredGroup is one required key together with the fields that can
550 // satisfy it; its position in structInfo.requiredGroups is its bitset index.
551 type requiredGroup struct {
552 key string
553 fields []fieldWithPrefix
554 }
555
556 // requiredPrefix names a group a nested source key can satisfy, with the
557 // field type that judges whether the key's value counts as non-empty.
558 type requiredPrefix struct {
559 typ reflect.Type
560 group int
561 }
562
563 type fieldWithPrefix struct {
564 *fieldInfo
565 prefix string
566 // searchPaths lists the src keys this required field answers to, and
567 // searchPathDots the corresponding nested-key prefixes; both are
568 // precomputed at cache-build time so per-request checks allocate
569 // nothing.
570 searchPaths []string
571 searchPathDots []string
572 }
573
574 func newFieldWithPrefix(f *fieldInfo, prefix string) fieldWithPrefix {
575 paths := f.paths(prefix)
576 dots := make([]string, len(paths))
577 for i, p := range paths {
578 dots[i] = p + "."
579 }
580 return fieldWithPrefix{
581 fieldInfo: f,
582 prefix: prefix,
583 searchPaths: paths,
584 searchPathDots: dots,
585 }
586 }
587
588 // directlyProvided reports whether any of the group's own paths carries a
589 // non-empty value in src.
590 func directlyProvided(fields []fieldWithPrefix, src *source) bool {
591 for _, f := range fields {
592 for _, path := range f.searchPaths {
593 if v, ok := src.lookup(path); ok && !isEmpty(f.typ, v) {
594 return true
595 }
596 }
597 }
598 return false
599 }
600
601 // isEmpty returns true if value is empty for specific type
602 func isEmpty(t reflect.Type, value []string) bool {
603 if len(value) == 0 {
604 return true
605 }
606 switch t.Kind() {
607 case boolType, float32Type, float64Type,
608 intType, int8Type, int16Type, int32Type, int64Type,
609 stringType,
610 uintType, uint8Type, uint16Type, uint32Type, uint64Type:
611 return len(value[0]) == 0
612 }
613 return false
614 }
615
616 var (
617 multipartFileHeaderPointerType = reflect.TypeOf(&multipart.FileHeader{})
618 sliceMultipartFileHeaderPointerType = reflect.TypeOf([]*multipart.FileHeader{})
619 )
620
621 // Supported multiple types:
622 // *multipart.FileHeader, *[]multipart.FileHeader, []*multipart.FileHeader
623 func handleMultipartField(field reflect.Value, files []*multipart.FileHeader) bool {
624 fieldType := field.Type()
625 if !isMultipartField(fieldType) {
626 return false
627 }
628
629 // Skip if files are empty and field is multipart
630 if len(files) == 0 {
631 return true
632 }
633
634 // Check for *multipart.FileHeader
635 if fieldType == multipartFileHeaderPointerType {
636 field.Set(reflect.ValueOf(files[0]))
637 return true
638 }
639
640 // Check for []*multipart.FileHeader
641 if fieldType == sliceMultipartFileHeaderPointerType {
642 field.Set(reflect.ValueOf(files))
643 return true
644 }
645
646 // Check for *[]*multipart.FileHeader
647 if fieldType.Kind() == reflect.Pointer {
648 fieldType = fieldType.Elem()
649
650 if field.IsNil() {
651 field.Set(reflect.New(fieldType))
652 }
653
654 if fieldType == sliceMultipartFileHeaderPointerType {
655 field.Elem().Set(reflect.ValueOf(files))
656 return true
657 }
658 }
659
660 return false
661 }
662
663 // Supported multiple types:
664 // *multipart.FileHeader, *[]multipart.FileHeader, []*multipart.FileHeader
665 func isMultipartField(typ reflect.Type) bool {
666 // Check for *multipart.FileHeader
667 if typ == multipartFileHeaderPointerType {
668 return true
669 }
670
671 // Check for []*multipart.FileHeader
672 if typ == sliceMultipartFileHeaderPointerType {
673 return true
674 }
675
676 // Check for *[]*multipart.FileHeader
677 if typ.Kind() == reflect.Ptr {
678 typ = typ.Elem()
679
680 if typ == sliceMultipartFileHeaderPointerType {
681 return true
682 }
683 }
684
685 return false
686 }
687
688 // walkHops follows a path to the target field, dereferencing pointers and
689 // allocating the embedded pointers promoted fields need on the way. It
690 // returns the zero Value when an unsettable nil embedded pointer blocks the
691 // walk.
692 func walkHops(v reflect.Value, hops []pathHop) reflect.Value {
693 for _, hop := range hops {
694 // A previous hop may have been blocked by an unsettable nil
695 // embedded pointer; the field is unreachable then.
696 if !v.IsValid() {
697 return v
698 }
699 if v.Kind() == reflect.Ptr {
700 if v.IsNil() {
701 v.Set(reflect.New(v.Type().Elem()))
702 }
703 v = v.Elem()
704 }
705
706 // Allocate embedded anonymous pointers required for promoted fields.
707 for _, idx := range hop.ensure {
708 if f := v.Field(idx); f.IsNil() {
709 f.Set(reflect.New(f.Type().Elem()))
710 }
711 }
712
713 v = walkIndexChain(v, hop.index)
714 }
715 return v
716 }
717
718 // walkIndexChain walks v along a struct field index chain. Chains longer
719 // than one element traverse embedded structs; intermediate nil pointers are
720 // allocated so promoted fields stay reachable. It returns the zero Value
721 // when the chain is blocked by a nil pointer that cannot be set (an
722 // unexported embedded pointer), which callers treat as an unreachable
723 // field.
724 func walkIndexChain(v reflect.Value, chain []int) reflect.Value {
725 for j, fi := range chain {
726 if j > 0 && v.Kind() == reflect.Ptr {
727 if v.IsNil() {
728 if !v.CanSet() {
729 return reflect.Value{}
730 }
731 v.Set(reflect.New(v.Type().Elem()))
732 }
733 v = v.Elem()
734 }
735 v = v.Field(fi)
736 }
737 return v
738 }
739
740 // growTracker remembers which of the destination struct's slice fields a
741 // Decode call has already reallocated, and how much room it reserved in each.
742 // Fields are keyed by their index in that struct, which is what pathPart's
743 // soleIndex carries: only a slice reached by one hop can be tracked, since a
744 // deeper path reaches a slice inside some element, which the field alone
745 // cannot tell apart from the same field in another. Fields past the four
746 // entries keep growing exactly.
747 type growTracker struct {
748 fields [4]int
749 caps [4]int
750 n int
751 }
752
753 // reserved returns the capacity this call gave the slice at struct field
754 // index i, or 0 if it has not reallocated it.
755 func (g *growTracker) reserved(i int) int {
756 for j := 0; j < g.n; j++ {
757 if g.fields[j] == i {
758 return g.caps[j]
759 }
760 }
761 return 0
762 }
763
764 func (g *growTracker) record(i, c int) {
765 for j := 0; j < g.n; j++ {
766 if g.fields[j] == i {
767 g.caps[j] = c
768 return
769 }
770 }
771 if g.n < len(g.fields) {
772 g.fields[g.n] = i
773 g.caps[g.n] = c
774 g.n++
775 }
776 }
777
778 // decode fills a struct field using a parsed path. grow is non-nil only for
779 // the outermost call, the one place slice growth can be tracked.
780 func (d *Decoder) decode(v reflect.Value, path string, parts []pathPart, values []string, files []*multipart.FileHeader, grow *growTracker) error {
781 // Get the field walking the struct fields by index. Almost every path is
782 // one hop into a field of v, which needs none of the loop's bookkeeping.
783 if idx := parts[0].soleIndex; idx >= 0 && v.Kind() == reflect.Struct {
784 v = v.Field(idx)
785 } else if v = walkHops(v, parts[0].hops); !v.IsValid() {
786 // Unreachable behind an unsettable nil embedded pointer.
787 return nil
788 }
789
790 // Don't even bother for unexported fields.
791 if !v.CanSet() {
792 return nil
793 }
794
795 // Fast path: plain builtin scalar fields skip the converter/unmarshaler
796 // dispatch below; fastKind was validated at cache-build time.
797 if k := parts[0].field.fastKind; k != reflect.Invalid && len(parts) == 1 && !parts[0].elem {
798 val := ""
799 if len(values) > 0 {
800 val = values[len(values)-1]
801 }
802 if val == "" {
803 if d.zeroEmpty {
804 v.SetZero()
805 }
806 return nil
807 }
808 if _, ok := setBuiltinKind(v, k, val); !ok {
809 return ConversionError{
810 Key: path,
811 Type: parts[0].field.typ,
812 Index: -1,
813 }
814 }
815 return nil
816 }
817
818 // Check multipart files
819 if parts[0].field.isMultipart && handleMultipartField(v, files) {
820 return nil
821 }
822
823 // Dereference if needed.
824 t := v.Type()
825 if t.Kind() == reflect.Ptr {
826 t = t.Elem()
827 if v.IsNil() {
828 v.Set(reflect.New(t))
829 }
830 v = v.Elem()
831 }
832
833 // Slice of structs. Let's go recursive.
834 if len(parts) > 1 {
835 idx := parts[0].index
836 // a defensive check to avoid creating a large slice based on user input index
837 if idx > d.maxSize {
838 return fmt.Errorf("%v index %d is larger than the configured maxSize %d", v.Kind(), idx, d.maxSize)
839 }
840 if n := idx + 1; v.IsNil() || v.Len() < n {
841 // Indices arrive in map order, so a slice is typically grown
842 // several times per call. Extending one this call allocated is
843 // free: the room past its length is ours and freshly zeroed.
844 owner := -1
845 if grow != nil {
846 owner = parts[0].soleIndex
847 }
848 if owner >= 0 && n <= v.Cap() && grow.reserved(owner) >= n {
849 v.SetLen(n)
850 } else {
851 // Otherwise grow into a fresh backing array: extending within
852 // the existing capacity would write into memory the caller
853 // may still share through another slice aliasing it.
854 value := reflect.MakeSlice(t, n, d.growCap(n, owner >= 0))
855 if v.Len() > 0 {
856 // Resize it.
857 reflect.Copy(value, v)
858 }
859 v.Set(value)
860 if owner >= 0 {
861 grow.record(owner, value.Cap())
862 }
863 }
864 }
865 return d.decode(v.Index(idx), path, parts[1:], values, files, nil)
866 }
867
868 // Get the converter early in case there is one for a slice type.
869 conv := d.cache.converter(t)
870 // The encoding.TextUnmarshaler facts for v's type are precomputed per
871 // field; instances are bound to live values where needed below. For an
872 // elem part (path terminated at a slice index) v is an element of the
873 // slice field, so the element type's facts apply.
874 m := parts[0].field.derefUnmarshaler
875 if parts[0].elem {
876 m = parts[0].field.elemUnmarshaler
877 }
878 if conv == nil && t.Kind() == reflect.Slice && m.IsSliceElement {
879 elemT := t.Elem()
880 isPtrElem := elemT.Kind() == reflect.Ptr
881 if isPtrElem {
882 elemT = elemT.Elem()
883 }
884
885 // Try to get a converter for the element type.
886 customConv := d.cache.converter(elemT)
887 conv := customConv
888 if conv == nil {
889 conv = getBuiltinConverter(elemT.Kind())
890 if conv == nil {
891 // As we are not dealing with slice of structs here, we don't need to check if the type
892 // implements TextUnmarshaler interface
893 return fmt.Errorf("schema: converter not found for %v", elemT)
894 }
895 }
896
897 // Fast path: builtin element kinds without unmarshalers, custom
898 // converters or pointer elements decode straight into a fresh slice,
899 // avoiding one reflect.Value allocation per element.
900 if customConv == nil && !m.IsValid && !isPtrElem {
901 return d.decodeBuiltinSlice(v, t, path, values)
902 }
903
904 return d.decodeBoxedSlice(v, t, elemT, path, values, conv, m, isPtrElem)
905 } else {
906 val := ""
907 // Use the last value provided if any values were provided
908 if len(values) > 0 {
909 val = values[len(values)-1]
910 }
911
912 if conv != nil {
913 if value := conv(val); value.IsValid() {
914 v.Set(value.Convert(t))
915 } else {
916 return ConversionError{
917 Key: path,
918 Type: t,
919 Index: -1,
920 }
921 }
922 } else if m.IsValid {
923 if m.IsPtr {
924 u := reflect.New(v.Type())
925 um, _ := reflect.TypeAssert[encoding.TextUnmarshaler](u)
926 if err := um.UnmarshalText([]byte(val)); err != nil {
927 return ConversionError{
928 Key: path,
929 Type: t,
930 Index: -1,
931 Err: err,
932 }
933 }
934 v.Set(reflect.Indirect(u))
935 } else {
936 // If the value implements the encoding.TextUnmarshaler interface
937 // apply UnmarshalText as the converter, binding it to the
938 // live value.
939 um, _ := reflect.TypeAssert[encoding.TextUnmarshaler](v)
940 if err := um.UnmarshalText([]byte(val)); err != nil {
941 return ConversionError{
942 Key: path,
943 Type: t,
944 Index: -1,
945 Err: err,
946 }
947 }
948 }
949 } else if val == "" {
950 if d.zeroEmpty {
951 v.Set(reflect.Zero(t))
952 }
953 } else if handled, ok := setBuiltinKind(v, t.Kind(), val); handled {
954 if !ok {
955 return ConversionError{
956 Key: path,
957 Type: t,
958 Index: -1,
959 }
960 }
961 } else {
962 return fmt.Errorf("schema: converter not found for %v", t)
963 }
964 }
965 return nil
966 }
967
968 // decodeBoxedSlice decodes values into the slice field v whose elements have
969 // to round-trip through a reflect.Value: a custom converter, a
970 // TextUnmarshaler, or pointer elements. It is split out so that decode, which
971 // runs once per source key, carries no defer of its own.
972 func (d *Decoder) decodeBoxedSlice(v reflect.Value, t, elemT reflect.Type, path string, values []string, conv Converter, m unmarshaler, isPtrElem bool) error {
973 itemsBuf := decodeValueBufferPool.Get().(*[]reflect.Value)
974 items := (*itemsBuf)[:0]
975 defer func() {
976 clear(items)
977 *itemsBuf = items[:0]
978 decodeValueBufferPool.Put(itemsBuf)
979 }()
980
981 for key, value := range values {
982 if value == "" {
983 if d.zeroEmpty {
984 items = append(items, reflect.Zero(t.Elem()))
985 }
986 } else if m.IsValid {
987 u := reflect.New(elemT)
988 if m.IsSliceElementPtr {
989 u = reflect.New(reflect.PointerTo(elemT).Elem())
990 }
991 um, _ := reflect.TypeAssert[encoding.TextUnmarshaler](u)
992 if err := um.UnmarshalText([]byte(value)); err != nil {
993 return ConversionError{
994 Key: path,
995 Type: t,
996 Index: key,
997 Err: err,
998 }
999 }
1000 if m.IsSliceElementPtr {
1001 items = append(items, u.Elem().Addr())
1002 } else {
1003 // u is always a pointer from reflect.New; store the
1004 // pointed-to value.
1005 items = append(items, u.Elem())
1006 }
1007 } else if item := conv(value); item.IsValid() {
1008 items = appendConvertedItem(items, item, elemT, isPtrElem)
1009 } else {
1010 if strings.IndexByte(value, ',') != -1 {
1011 for value := range strings.SplitSeq(value, ",") {
1012 if value == "" {
1013 if d.zeroEmpty {
1014 items = append(items, reflect.Zero(t.Elem()))
1015 }
1016 } else if item := conv(value); item.IsValid() {
1017 items = appendConvertedItem(items, item, elemT, isPtrElem)
1018 } else {
1019 return ConversionError{
1020 Key: path,
1021 Type: elemT,
1022 Index: key,
1023 }
1024 }
1025 }
1026 } else {
1027 return ConversionError{
1028 Key: path,
1029 Type: elemT,
1030 Index: key,
1031 }
1032 }
1033 }
1034 }
1035 value := reflect.MakeSlice(t, len(items), len(items))
1036 for i, item := range items {
1037 value.Index(i).Set(item)
1038 }
1039 v.Set(value)
1040 return nil
1041 }
1042
1043 // appendConvertedItem converts a builtin/custom converter result to the slice
1044 // element type and appends it, wrapping it in a freshly allocated pointer for
1045 // pointer-element slices. The conversion must happen before the pointer wrap:
1046 // builtin converters return the underlying kind (e.g. int for a named
1047 // `type MyInt int`), which is not assignable to the named element type, so
1048 // Set-ing it into a *MyInt without converting first panics.
1049 func appendConvertedItem(items []reflect.Value, item reflect.Value, elemT reflect.Type, isPtrElem bool) []reflect.Value {
1050 if item.Type() != elemT {
1051 item = item.Convert(elemT)
1052 }
1053 if isPtrElem {
1054 ptr := reflect.New(elemT)
1055 ptr.Elem().Set(item)
1056 item = ptr
1057 }
1058 return append(items, item)
1059 }
1060
1061 // decodeBuiltinSlice decodes values into the slice field v of type t whose
1062 // elements are builtin-convertible kinds, parsing directly into slice slots
1063 // instead of boxing every element in a reflect.Value. The slice is built
1064 // detached and only assigned to v when every value parsed, matching the
1065 // all-or-nothing behavior of the generic path.
1066 //
1067 // A value that fails to parse as a whole is retried as a comma-separated
1068 // list. For non-string kinds a value containing a comma can never parse as a
1069 // whole (no builtin syntax admits commas — pinned by a test), and string
1070 // values always parse, so item boundaries are knowable upfront: the slice is
1071 // sized by a cheap comma count (an upper bound, since empty items may be
1072 // skipped) and truncated to the filled length at the end.
1073 func (d *Decoder) decodeBuiltinSlice(v reflect.Value, t reflect.Type, path string, values []string) error {
1074 elemT := t.Elem()
1075 k := elemT.Kind()
1076 split := k != reflect.String
1077
1078 n := len(values)
1079 if split {
1080 for _, value := range values {
1081 n += strings.Count(value, ",")
1082 }
1083 // The counts already say whether any value holds a separator, so
1084 // when none does the per-value scans below have nothing to find.
1085 split = n > len(values)
1086 }
1087
1088 // Exact builtin slice types decode without per-element reflect calls;
1089 // named slice or element types fall through to the generic path.
1090 switch t {
1091 case typSliceString:
1092 return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeString)
1093 case typSliceInt:
1094 return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeInt)
1095 case typSliceInt64:
1096 return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeInt64)
1097 case typSliceUint:
1098 return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeUint)
1099 case typSliceUint64:
1100 return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeUint64)
1101 case typSliceFloat64:
1102 return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeFloat64)
1103 case typSliceBool:
1104 return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeBool)
1105 }
1106
1107 sl := reflect.MakeSlice(t, n, n)
1108 i := 0
1109 for key, value := range values {
1110 switch {
1111 case value == "":
1112 if d.zeroEmpty {
1113 i++ // slot stays zero
1114 }
1115 case split && strings.IndexByte(value, ',') != -1:
1116 for item := range strings.SplitSeq(value, ",") {
1117 if item == "" {
1118 if d.zeroEmpty {
1119 i++ // slot stays zero
1120 }
1121 continue
1122 }
1123 if _, ok := setBuiltinKind(sl.Index(i), k, item); !ok {
1124 return ConversionError{
1125 Key: path,
1126 Type: elemT,
1127 Index: key,
1128 }
1129 }
1130 i++
1131 }
1132 default:
1133 if _, ok := setBuiltinKind(sl.Index(i), k, value); !ok {
1134 return ConversionError{
1135 Key: path,
1136 Type: elemT,
1137 Index: key,
1138 }
1139 }
1140 i++
1141 }
1142 }
1143 if i < n {
1144 sl = sl.Slice(0, i)
1145 }
1146 v.Set(sl)
1147 return nil
1148 }
1149
1150 // Exact (unnamed) builtin slice types eligible for the native decode path.
1151 var (
1152 typSliceString = reflect.TypeOf([]string(nil))
1153 typSliceInt = reflect.TypeOf([]int(nil))
1154 typSliceInt64 = reflect.TypeOf([]int64(nil))
1155 typSliceUint = reflect.TypeOf([]uint(nil))
1156 typSliceUint64 = reflect.TypeOf([]uint64(nil))
1157 typSliceFloat64 = reflect.TypeOf([]float64(nil))
1158 typSliceBool = reflect.TypeOf([]bool(nil))
1159 )
1160
1161 // decodeNativeSlice mirrors the generic decodeBuiltinSlice loop for a field
1162 // typed exactly []T, parsing into a native slice assigned only if every value
1163 // parsed (all-or-nothing). n is the precomputed element upper bound.
1164 func decodeNativeSlice[T any](zeroEmpty bool, v reflect.Value, path string, values []string, elemT reflect.Type, n int, split bool, parse func(string) (T, bool)) error {
1165 out := make([]T, 0, n)
1166 var zero T
1167 for key, value := range values {
1168 switch {
1169 case value == "":
1170 if zeroEmpty {
1171 out = append(out, zero)
1172 }
1173 case split && strings.IndexByte(value, ',') != -1:
1174 for item := range strings.SplitSeq(value, ",") {
1175 if item == "" {
1176 if zeroEmpty {
1177 out = append(out, zero)
1178 }
1179 continue
1180 }
1181 ev, ok := parse(item)
1182 if !ok {
1183 return ConversionError{
1184 Key: path,
1185 Type: elemT,
1186 Index: key,
1187 }
1188 }
1189 out = append(out, ev)
1190 }
1191 default:
1192 ev, ok := parse(value)
1193 if !ok {
1194 return ConversionError{
1195 Key: path,
1196 Type: elemT,
1197 Index: key,
1198 }
1199 }
1200 out = append(out, ev)
1201 }
1202 }
1203 // v's type is exactly []T here (the dispatch switch guarantees it), and v
1204 // is settable (decode returns before reaching here for a field it cannot
1205 // set), so assign through a typed pointer to it: no reflect.ValueOf
1206 // escape and no Set assignability checks. The pointer comes from
1207 // UnsafeAddr rather than Addr().Interface(), which resolved the pointer
1208 // type on every call and measured a fifth of the whole assignment's cost.
1209 *(*[]T)(unsafe.Pointer(v.UnsafeAddr())) = out
1210 return nil
1211 }
1212
1213 func isTextUnmarshaler(v reflect.Value) unmarshaler {
1214 // Create a new unmarshaller instance
1215 m := unmarshaler{}
1216 if _, m.IsValid = reflect.TypeAssert[encoding.TextUnmarshaler](v); m.IsValid {
1217 return m
1218 }
1219 // As the UnmarshalText function should be applied to the pointer of the
1220 // type, we check that type to see if it implements the necessary
1221 // method.
1222 if _, m.IsValid = reflect.TypeAssert[encoding.TextUnmarshaler](reflect.New(v.Type())); m.IsValid {
1223 m.IsPtr = true
1224 return m
1225 }
1226
1227 // if v is []T or *[]T create new T
1228 t := v.Type()
1229 if t.Kind() == reflect.Ptr {
1230 t = t.Elem()
1231 }
1232 if t.Kind() == reflect.Slice {
1233 // The slice type itself cannot implement encoding.TextUnmarshaler
1234 // here: the value-level assert above already covered it. Check
1235 // whether the elements do.
1236 m.IsSliceElement = true
1237 if t = t.Elem(); t.Kind() == reflect.Ptr {
1238 t = reflect.PointerTo(t.Elem())
1239 m.IsSliceElementPtr = true
1240 _, m.IsValid = reflect.TypeAssert[encoding.TextUnmarshaler](reflect.Zero(t))
1241 return m
1242 }
1243 }
1244
1245 _, m.IsValid = reflect.TypeAssert[encoding.TextUnmarshaler](reflect.New(t))
1246 return m
1247 }
1248
1249 // TextUnmarshaler helpers ----------------------------------------------------
1250 // unmarshaler describes how a type relates to encoding.TextUnmarshaler.
1251 // It carries type-level facts only; the decoder binds instances to live
1252 // values at the point of use.
1253 type unmarshaler struct {
1254 // IsValid indicates whether the resolved type indicated by the other
1255 // flags implements the encoding.TextUnmarshaler interface.
1256 IsValid bool
1257 // IsPtr indicates that the resolved type is the pointer of the original
1258 // type.
1259 IsPtr bool
1260 // IsSliceElement indicates that the resolved type is a slice element of
1261 // the original type.
1262 IsSliceElement bool
1263 // IsSliceElementPtr indicates that the resolved type is a pointer to a
1264 // slice element of the original type.
1265 IsSliceElementPtr bool
1266 }
1267
1268 // Errors ---------------------------------------------------------------------
1269
1270 // ConversionError stores information about a failed conversion.
1271 type ConversionError struct {
1272 Key string // key from the source map.
1273 Type reflect.Type // expected type of elem
1274 Index int // index for multi-value fields; -1 for single-value fields.
1275 Err error // low-level error (when it exists)
1276 }
1277
1278 // The error strings below are assembled by concatenation instead of
1279 // fmt.Sprintf: %q is strconv.Quote and %d is utils.FormatInt, so the messages
1280 // are byte-identical without the reflection-based formatter.
1281 func (e ConversionError) Error() string {
1282 var output string
1283
1284 if e.Index < 0 {
1285 output = "schema: error converting value for " + strconv.Quote(e.Key)
1286 } else {
1287 output = "schema: error converting value for index " +
1288 utils.FormatInt(int64(e.Index)) + " of " + strconv.Quote(e.Key)
1289 }
1290
1291 if e.Err != nil {
1292 output += ". Details: " + e.Err.Error()
1293 }
1294
1295 return output
1296 }
1297
1298 // UnknownKeyError stores information about an unknown key in the source map.
1299 type UnknownKeyError struct {
1300 Key string // key from the source map.
1301 }
1302
1303 func (e UnknownKeyError) Error() string {
1304 return "schema: invalid path " + strconv.Quote(e.Key)
1305 }
1306
1307 // EmptyFieldError stores information about an empty required field.
1308 type EmptyFieldError struct {
1309 Key string // required key in the source map.
1310 }
1311
1312 func (e EmptyFieldError) Error() string {
1313 return e.Key + " is empty"
1314 }
1315
1316 // MultiError stores multiple decoding errors.
1317 //
1318 // Borrowed from the App Engine SDK.
1319 type MultiError map[string]error
1320
1321 func (e MultiError) Error() string {
1322 s := ""
1323 for _, err := range e {
1324 s = err.Error()
1325 break
1326 }
1327 switch len(e) {
1328 case 0:
1329 return "(0 errors)"
1330 case 1:
1331 return s
1332 case 2:
1333 return s + " (and 1 other error)"
1334 }
1335 return s + " (and " + utils.FormatInt(int64(len(e)-1)) + " other errors)"
1336 }
1337
1338 func appendError(m MultiError, key string, err error) MultiError {
1339 if err == nil {
1340 return m
1341 }
1342 if m == nil {
1343 m = make(MultiError)
1344 }
1345 if m[key] == nil {
1346 m[key] = err
1347 }
1348 return m
1349 }
1350
1351 func mergeErrors(dst, src MultiError) MultiError {
1352 if len(src) == 0 {
1353 return dst
1354 }
1355 if dst == nil {
1356 dst = make(MultiError, len(src))
1357 }
1358 for key, err := range src {
1359 if dst[key] == nil {
1360 dst[key] = err
1361 }
1362 }
1363 return dst
1364 }