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