Debian Codegraph @

cache.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 "errors"
9 "maps"
10 "reflect"
11 "strings"
12 "sync"
13 "sync/atomic"
14 "unsafe"
15
16 utils "github.com/gofiber/utils/v2"
17 utilstrings "github.com/gofiber/utils/v2/strings"
18 "github.com/gofiber/utils/v2/swar"
19 )
20
21 const maxParserIndex = 1000
22
23 // maxDirectKeyLen bounds the stack buffers keys are case-folded or assembled
24 // in for a map probe; longer keys take a path that allocates.
25 const maxDirectKeyLen = 64
26
27 // maxDirectPaths caps the nested entries precomputed per struct type: deep
28 // fan-out nesting multiplies dotted chains, and without a cap build time and
29 // retained memory grow exponentially. Excess keys use the generic parser.
30 const maxDirectPaths = 512
31
32 // maxPathReserve caps the hop and part slices the parser reserves from a
33 // path's separator count. That count comes from a key nothing has validated
34 // yet, so an unbounded reservation lets a key of mostly separators claim
35 // megabytes before its first segment is rejected. Appending past the
36 // reservation still works, and real paths are a few segments deep.
37 const maxPathReserve = 16
38
39 var (
40 errInvalidPath = errors.New("schema: invalid path")
41 errIndexTooLarge = errors.New("schema: index exceeds parser limit")
42 )
43
44 // newCache returns a new cache.
45 func newCache() *cache {
46 c := cache{
47 tag: "schema",
48 }
49 return &c
50 }
51
52 // cache caches meta-data about a struct.
53 type cache struct {
54 l sync.RWMutex // serializes configuration writes (tag, regconv)
55 m sync.Map // map[reflect.Type]cacheEntry
56 // regconv holds the registered converters as an immutable map published
57 // atomically: registerConverter replaces the whole map (copy-on-write
58 // under l), so readers never touch a map that is being written.
59 regconv atomic.Pointer[map[reflect.Type]Converter]
60 tag string
61 // gen is bumped (under l) before m is cleared on configuration changes;
62 // cached entries are tagged with the generation they were built under
63 // and ignored on mismatch, so any call starting after a reconfiguration
64 // returns observes the new configuration even if a racing build stored
65 // a stale entry after the clear.
66 gen atomic.Uint64
67 // slots is a direct-mapped cache in front of m, indexed by the address
68 // of the type's descriptor: a hit costs a few loads and a compare, where
69 // m's interface-keyed hash was the largest part of what Decode paid to
70 // find a type's metadata. Entries are m's own, generation included, so
71 // a collision or a stale entry only falls through to m.
72 slots [typeCacheSlots]atomic.Pointer[cacheEntry]
73 }
74
75 // typeCacheSlots is the size of cache.slots, a power of two so a slot is a
76 // mask rather than a division.
77 const typeCacheSlots = 32
78
79 // typeSlot returns the cache.slots index of t: bits of the address of its
80 // type descriptor, the data word of the reflect.Type interface, read
81 // directly since reflect.ValueOf(t).Pointer() costs several times as much.
82 func typeSlot(t reflect.Type) uintptr {
83 return (*[2]uintptr)(unsafe.Pointer(&t))[1] >> 4 & (typeCacheSlots - 1)
84 }
85
86 // cacheEntry tags a structInfo with its type and the configuration
87 // generation it was built under; entries are stored by pointer in c.m
88 // (matching the encoder's encPlan pattern) and in c.slots.
89 type cacheEntry struct {
90 info *structInfo
91 typ reflect.Type
92 gen uint64
93 }
94
95 // registerConverter registers a converter function for a custom type.
96 func (c *cache) registerConverter(value interface{}, converterFunc Converter) {
97 c.l.Lock()
98 next := make(map[reflect.Type]Converter)
99 if prev := c.regconv.Load(); prev != nil {
100 maps.Copy(next, *prev)
101 }
102 next[reflect.TypeOf(value)] = converterFunc
103 c.regconv.Store(&next)
104 c.reset()
105 c.l.Unlock()
106 }
107
108 // parsePath parses a path in dotted notation verifying that it is a valid
109 // path to a struct field.
110 //
111 // It returns "path parts" which contain indices to fields to be used by
112 // reflect.Value.FieldByString(). Multiple parts are required for slices of
113 // structs.
114 func (c *cache) parsePath(p string, t reflect.Type) ([]pathPart, error) {
115 if t.Kind() != reflect.Struct {
116 return nil, errInvalidPath
117 }
118 return c.parsePathInfo(p, c.get(t))
119 }
120
121 // parsePathInfo is parsePath with the root struct's info already resolved,
122 // letting Decode look it up once per call instead of once per key. The
123 // parsed-path cache lives on that structInfo, keyed by the plain path
124 // string, which hashes much cheaper than a composite key.
125 func (c *cache) parsePathInfo(p string, rootInfo *structInfo) ([]pathPart, error) {
126 // Fast path: probe the precomputed direct paths, whose index matches the
127 // key case-insensitively in one probe, as the fields do.
128 if rootInfo.directIndex.len > 0 {
129 if parts, ok := rootInfo.directIndex.lookup(p); ok {
130 return parts, nil
131 }
132 // Every field a bare alias can reach is in the direct paths
133 // (buildDirectPaths adds the flat aliases before the cap can
134 // truncate anything), and the probe matched the key folded, so a
135 // dotless miss names no field.
136 if strings.IndexByte(p, '.') < 0 {
137 return nil, errInvalidPath
138 }
139 }
140
141 if cached, ok := rootInfo.paths.load(p); ok {
142 return cached, nil
143 }
144
145 struc := rootInfo
146 var t reflect.Type
147 var field *fieldInfo
148 var index64 int64
149 // A path yields at most one hop and one part per segment. The hops of
150 // every part share one backing array, cut into capped slices as the
151 // parts are emitted.
152 segments := min(strings.Count(p, ".")+1, maxPathReserve)
153 parts := make([]pathPart, 0, segments)
154 hopBuf := make([]pathHop, 0, segments)
155 hopStart := 0
156 for keyStart := 0; ; {
157 keyEnd, segment, err := nextPathSegment(p, keyStart)
158 if err != nil {
159 return nil, errInvalidPath
160 }
161 if field = struc.get(segment); field == nil {
162 return nil, errInvalidPath
163 }
164 // Valid field. Append the hop; the field's index chain was resolved
165 // when the structInfo was built, so the decoder walks plain indices
166 // instead of repeating FieldByName lookups on every Decode call.
167 hopBuf = append(hopBuf, pathHop{index: field.index, ensure: struc.anonymousPtrFields})
168 if field.takesIndex() {
169 // Parse a special case: slices of structs.
170 // i+1 must be the slice index.
171 //
172 // Now that struct can implements TextUnmarshaler interface,
173 // we don't need to force the struct's fields to appear in the path.
174 // So checking i+2 is not necessary anymore.
175 // We can skip this part if the type is multipart.FileHeader. It is another special case too.
176 keyStart = keyEnd + 1
177 if keyStart >= len(p) {
178 return nil, errInvalidPath
179 }
180 keyEnd, segment, err = nextPathSegment(p, keyStart)
181 if err != nil {
182 return nil, errInvalidPath
183 }
184 if index64, err = utils.ParseInt(segment); err != nil {
185 return nil, errInvalidPath
186 }
187 if index64 > maxParserIndex {
188 return nil, errIndexTooLarge
189 }
190 hops := hopBuf[hopStart:len(hopBuf):len(hopBuf)]
191 hopStart = len(hopBuf)
192 parts = append(parts, pathPart{
193 hops: hops,
194 field: field,
195 index: int(index64),
196 soleIndex: soleHopIndex(hops),
197 })
198
199 // Get the next struct type, dropping ptrs.
200 if field.typ.Kind() == reflect.Ptr {
201 t = field.typ.Elem()
202 } else {
203 t = field.typ
204 }
205 if t.Kind() == reflect.Slice {
206 t = t.Elem()
207 if t.Kind() == reflect.Ptr {
208 t = t.Elem()
209 }
210 }
211 } else if field.typ.Kind() == reflect.Ptr {
212 t = field.typ.Elem()
213 } else {
214 t = field.typ
215 }
216
217 if keyEnd == len(p) {
218 break
219 }
220 keyStart = keyEnd + 1
221 if keyStart >= len(p) {
222 return nil, errInvalidPath
223 }
224 if t.Kind() != reflect.Struct {
225 return nil, errInvalidPath
226 }
227 struc = c.get(t)
228 }
229 // Add the remaining. A part without hops means the path terminated at a
230 // slice index ("a.0"), so the decoder receives a slice element there.
231 hops := hopBuf[hopStart:len(hopBuf):len(hopBuf)]
232 parts = append(parts, pathPart{
233 hops: hops,
234 field: field,
235 index: -1,
236 soleIndex: soleHopIndex(hops),
237 elem: len(hops) == 0,
238 })
239
240 // Detach the key: callers may pass strings aliasing reused request buffers.
241 cached, _ := rootInfo.paths.loadOrStore(strings.Clone(p), parts)
242 return cached, nil
243 }
244
245 // maxFastPaths bounds pathCache's copy-on-write map: each publish copies the
246 // whole map, so past this many paths further entries spill instead. Real
247 // structs stay well inside it.
248 const maxFastPaths = 512
249
250 // pathCache caches parsed paths for one struct type, keyed by the raw source
251 // key. Lookups run against a plain string-keyed map published atomically —
252 // sync.Map's interface keys cost a type hash and a trie walk, and
253 // parsePathInfo probes once per source key. Writes copy the map under the
254 // lock, so a reader only ever sees a complete one.
255 type pathCache struct {
256 fast atomic.Pointer[map[string][]pathPart]
257 // spill holds paths seen after fast was sealed, so a key space larger
258 // than maxFastPaths keeps its cache.
259 spill sync.Map // map[string][]pathPart
260 mu sync.Mutex
261 sealed atomic.Bool
262 }
263
264 func (c *pathCache) load(key string) ([]pathPart, bool) {
265 if m := c.fast.Load(); m != nil {
266 if parts, ok := (*m)[key]; ok {
267 return parts, true
268 }
269 }
270 // spill only ever receives entries once fast is sealed.
271 if c.sealed.Load() {
272 if v, ok := c.spill.Load(key); ok {
273 return v.([]pathPart), true
274 }
275 }
276 return nil, false
277 }
278
279 // loadOrStore caches parts under key, or returns what a concurrent call
280 // cached there first.
281 func (c *pathCache) loadOrStore(key string, parts []pathPart) ([]pathPart, bool) {
282 if !c.sealed.Load() {
283 c.mu.Lock()
284 old := c.fast.Load()
285 if old != nil {
286 if existing, ok := (*old)[key]; ok {
287 c.mu.Unlock()
288 return existing, true
289 }
290 }
291 if old == nil || len(*old) < maxFastPaths {
292 var next map[string][]pathPart
293 if old == nil {
294 next = make(map[string][]pathPart, 1)
295 } else {
296 next = make(map[string][]pathPart, len(*old)+1)
297 maps.Copy(next, *old)
298 }
299 next[key] = parts
300 c.fast.Store(&next)
301 c.mu.Unlock()
302 return parts, false
303 }
304 c.sealed.Store(true)
305 c.mu.Unlock()
306 }
307 v, loaded := c.spill.LoadOrStore(key, parts)
308 return v.([]pathPart), loaded
309 }
310
311 func (c *pathCache) clear() {
312 c.mu.Lock()
313 c.fast.Store(nil)
314 // Nothing reaches spill before the seal, so an unsealed cache has none.
315 if c.sealed.Load() {
316 c.spill.Clear()
317 c.sealed.Store(false)
318 }
319 c.mu.Unlock()
320 }
321
322 // foldASCIILower writes the ASCII-lowercased form of s into buf and reports
323 // whether any byte changed. Folding into a caller-owned stack buffer lets the
324 // case-insensitive map probes below skip the allocation utilstrings.ToLower
325 // makes for a mixed-case key. The caller guarantees len(buf) >= len(s).
326 func foldASCIILower(buf []byte, s string) bool {
327 n := len(s)
328 changed := false
329 i := 0
330 for ; i+swar.WordLen <= n; i += swar.WordLen {
331 w := swar.Load8(s, i)
332 lw := swar.ToLowerWord(w)
333 changed = changed || lw != w
334 swar.Store8(buf, i, lw)
335 }
336 for ; i < n; i++ {
337 ch := s[i]
338 if ch >= 'A' && ch <= 'Z' {
339 ch += 'a' - 'A'
340 changed = true
341 }
342 buf[i] = ch
343 }
344 return changed
345 }
346
347 // dotBroadcast is the SWAR needle for '.'; hoisted so the word loop in
348 // nextPathSegment pays no per-call broadcast cost.
349 var dotBroadcast = swar.Broadcast('.')
350
351 func nextPathSegment(path string, start int) (int, string, error) {
352 end := start
353 for end+swar.WordLen <= len(path) {
354 if m := swar.ZeroLanes(swar.Load8(path, end) ^ dotBroadcast); m != 0 {
355 end += swar.FirstLane(m)
356 if start == end {
357 return 0, "", errInvalidPath
358 }
359 return end, path[start:end], nil
360 }
361 end += swar.WordLen
362 }
363 for end < len(path) && path[end] != '.' {
364 end++
365 }
366 if start == end {
367 return 0, "", errInvalidPath
368 }
369 return end, path[start:end], nil
370 }
371
372 // get returns a cached structInfo, creating it if necessary.
373 func (c *cache) get(t reflect.Type) *structInfo {
374 gen := c.gen.Load()
375 slot := &c.slots[typeSlot(t)]
376 // Ignore entries built under an older configuration: a build racing a
377 // reconfiguration may store one after the clear. Hit-validation
378 // guarantees that any call starting after the reconfiguration returned
379 // observes the new configuration (a call already in flight during the
380 // reconfiguration may still briefly use old metadata, which is inherent
381 // to concurrent reconfiguration).
382 cur := slot.Load()
383 if cur != nil && cur.typ == t && cur.gen == gen {
384 return cur.info
385 }
386 if v, ok := c.m.Load(t); ok {
387 if e := v.(*cacheEntry); e.gen == gen {
388 claimSlot(slot, cur, e)
389 return e.info
390 }
391 }
392 info := c.create(t, "")
393 if c.gen.Load() == gen {
394 e := &cacheEntry{info: info, typ: t, gen: gen}
395 c.m.Store(t, e)
396 claimSlot(slot, cur, e)
397 }
398 // If the configuration changed while building, serve the result once
399 // without caching it (or with a stale tag that hit-validation ignores);
400 // the next call rebuilds fresh.
401 return info
402 }
403
404 // claimSlot stores e in slot, which held cur when get read it, unless cur is
405 // the live entry of another type: two types sharing a slot would otherwise
406 // take it from each other on every call, and each store would invalidate the
407 // slots' cache line on every core reading it. A later type that loses the
408 // slot finds its metadata in c.m, as every type did before the slots.
409 func claimSlot(slot *atomic.Pointer[cacheEntry], cur, e *cacheEntry) {
410 if cur == nil || cur.gen < e.gen {
411 slot.CompareAndSwap(cur, e)
412 }
413 }
414
415 // reset clears cached metadata and must be called with c.l held. Parsed
416 // path caches live on the structInfos, so dropping them drops those too.
417 func (c *cache) reset() {
418 c.gen.Add(1)
419 c.m.Clear()
420 // The generation already turns the slots' entries away; dropping them
421 // lets their metadata go.
422 for i := range c.slots {
423 c.slots[i].Store(nil)
424 }
425 }
426
427 // aliasTag returns the configured tag name under the configuration lock, so
428 // metadata builds racing SetAliasTag read a consistent value.
429 func (c *cache) aliasTag() string {
430 c.l.RLock()
431 tag := c.tag
432 c.l.RUnlock()
433 return tag
434 }
435
436 // create creates a structInfo with meta-data about a struct.
437 func (c *cache) create(t reflect.Type, parentAlias string) *structInfo {
438 // Snapshot the alias tag once so every field of this type is analyzed
439 // under a consistent configuration and we don't churn the config lock
440 // per field.
441 tag := c.aliasTag()
442 info := &structInfo{}
443 var anonymousInfos []*structInfo
444 var anonymousIdx [][]int
445 for i := 0; i < t.NumField(); i++ {
446 structField := t.Field(i)
447 // Only exported anonymous pointers can be allocated; unexported ones
448 // are not settable and Set would panic.
449 if structField.Anonymous && structField.Type.Kind() == reflect.Ptr && structField.IsExported() {
450 info.anonymousPtrFields = append(info.anonymousPtrFields, i)
451 }
452 if f := c.createField(structField, parentAlias, tag); f != nil {
453 f.index = structField.Index
454 info.fields = append(info.fields, f)
455 if ft := indirectType(f.typ); ft.Kind() == reflect.Struct && f.isAnonymous {
456 anonymousInfos = append(anonymousInfos, c.create(ft, f.canonicalAlias))
457 anonymousIdx = append(anonymousIdx, structField.Index)
458 }
459 }
460 }
461 for i, a := range anonymousInfos {
462 others := []*structInfo{info}
463 others = append(others, anonymousInfos[:i]...)
464 others = append(others, anonymousInfos[i+1:]...)
465 for _, f := range a.fields {
466 if !containsAlias(others, f.alias) {
467 // Copy the promoted field so its index chain can be prefixed
468 // with the embedded field's index; the original stays valid
469 // for the embedded type's own structInfo.
470 pf := *f
471 pf.index = append(append(make([]int, 0, len(anonymousIdx[i])+len(f.index)), anonymousIdx[i]...), f.index...)
472 info.fields = append(info.fields, &pf)
473 }
474 }
475 }
476 info.fieldsByName = make(map[string]*fieldInfo, len(info.fields))
477 for _, field := range info.fields {
478 if _, exists := info.fieldsByName[field.aliasLower]; !exists {
479 info.fieldsByName[field.aliasLower] = field
480 }
481 }
482 for _, f := range info.fields {
483 if f.takesIndex() {
484 info.hasIndexedSlice = true
485 }
486 if k := f.typ.Kind(); f.def != nil || k == reflect.Struct ||
487 (k == reflect.Ptr && f.typ.Elem().Kind() == reflect.Struct) {
488 info.defaultFields = append(info.defaultFields, f)
489 }
490 }
491 info.requiredGroups = c.buildRequiredFields(info)
492 info.requiredPrefixes = buildRequiredPrefixes(info.requiredGroups)
493 info.direct = c.buildDirectPaths(info)
494 info.directIndex = newFoldIndex(info.direct)
495 // The setDefaults walk also allocates nil anonymous embedded pointers,
496 // so it can only be skipped when neither defaults nor such pointers
497 // exist anywhere in the tree.
498 info.needsDefaultsWalk = c.needsDefaultsWalk(t, tag, map[reflect.Type]bool{})
499 return info
500 }
501
502 // buildDirectPaths precomputes, keyed by lowercase path, the parsed paths for
503 // every key resolvable without runtime state: flat aliases plus dotted chains
504 // through non-pointer nested struct fields.
505 func (c *cache) buildDirectPaths(info *structInfo) map[string][]pathPart {
506 direct := make(map[string][]pathPart, len(info.fieldsByName))
507 // Flat aliases first (linear in field count) so the cap below can never
508 // crowd them out; iterate fields in declaration order, honoring
509 // fieldsByName's first-wins rule.
510 for _, f := range info.fields {
511 if !directEligible(info, f) {
512 continue
513 }
514 hops := []pathHop{{index: f.index, ensure: info.anonymousPtrFields}}
515 direct[f.aliasLower] = []pathPart{{
516 hops: hops,
517 field: f,
518 index: -1,
519 soleIndex: soleHopIndex(hops),
520 }}
521 }
522 for _, f := range info.fields {
523 if len(direct) >= maxDirectPaths {
524 break
525 }
526 if !directEligible(info, f) || f.typ.Kind() != reflect.Struct {
527 continue
528 }
529 // Non-pointer struct nesting cannot recurse (the type would be
530 // illegal), so the child's info is always buildable here.
531 hop := pathHop{index: f.index, ensure: info.anonymousPtrFields}
532 for childKey, childParts := range c.get(f.typ).direct {
533 if len(direct) >= maxDirectPaths {
534 break
535 }
536 cp := childParts[0]
537 hops := make([]pathHop, 0, len(cp.hops)+1)
538 hops = append(hops, hop)
539 hops = append(hops, cp.hops...)
540 direct[f.aliasLower+"."+childKey] = []pathPart{{
541 hops: hops,
542 field: cp.field,
543 index: -1,
544 soleIndex: soleHopIndex(hops),
545 }}
546 }
547 }
548 return direct
549 }
550
551 // directEligible reports whether f can serve as a direct-path terminal: it is
552 // its alias's first-wins winner, the alias has no dot, and a bare alias is a
553 // valid path (slice-of-structs fields require a following slice index).
554 func directEligible(info *structInfo, f *fieldInfo) bool {
555 if info.fieldsByName[f.aliasLower] != f || strings.IndexByte(f.aliasLower, '.') >= 0 {
556 return false
557 }
558 return !f.takesIndex()
559 }
560
561 // takesIndex reports whether a path through f must carry a slice element
562 // index: f is a slice of structs walked element by element, not one handed to
563 // a multipart binder or a TextUnmarshaler whole.
564 func (f *fieldInfo) takesIndex() bool {
565 return f.isSliceOfStructs && !f.isMultipart &&
566 (!f.unmarshalerInfo.IsValid || f.unmarshalerInfo.IsSliceElement)
567 }
568
569 // needsDefaultsWalk reports whether the setDefaults walk can have any effect
570 // on the struct tree rooted at t: it declares a default tag option, or has an
571 // (exported) anonymous pointer field the walk allocates, anywhere in the
572 // tree. visited guards against recursive types. tag is the alias tag
573 // snapshot for this build, so no per-field config lock is taken.
574 func (c *cache) needsDefaultsWalk(t reflect.Type, tag string, visited map[reflect.Type]bool) bool {
575 if t.Kind() == reflect.Ptr {
576 t = t.Elem()
577 }
578 if t.Kind() != reflect.Struct || visited[t] {
579 return false
580 }
581 visited[t] = true
582 for i := 0; i < t.NumField(); i++ {
583 field := t.Field(i)
584 // Mirror the anonymousPtrFields filter: only exported anonymous
585 // pointers are ever allocated, so only they justify the walk.
586 if field.Anonymous && field.Type.Kind() == reflect.Ptr && field.IsExported() {
587 return true
588 }
589 alias, options := fieldAlias(field, tag)
590 if alias == "-" {
591 continue
592 }
593 if options.getDefaultOptionValue() != "" {
594 return true
595 }
596 if c.needsDefaultsWalk(field.Type, tag, visited) {
597 return true
598 }
599 }
600 return false
601 }
602
603 // createField creates a fieldInfo for the given field. tag is the alias tag
604 // snapshot for the enclosing type's build.
605 func (c *cache) createField(field reflect.StructField, parentAlias, tag string) *fieldInfo {
606 alias, options := fieldAlias(field, tag)
607 if alias == "-" {
608 // Ignore this field.
609 return nil
610 }
611 canonicalAlias := alias
612 if parentAlias != "" {
613 canonicalAlias = parentAlias + "." + alias
614 }
615 // Check if the type is supported and don't cache it if not.
616 // First let's get the basic type.
617 isSlice, isStruct := false, false
618 ft := field.Type
619 m := isTextUnmarshaler(reflect.Zero(ft))
620 if ft.Kind() == reflect.Ptr {
621 ft = ft.Elem()
622 }
623 if isSlice = ft.Kind() == reflect.Slice; isSlice {
624 ft = ft.Elem()
625 if ft.Kind() == reflect.Ptr {
626 ft = ft.Elem()
627 }
628 }
629 if ft.Kind() == reflect.Array {
630 ft = ft.Elem()
631 if ft.Kind() == reflect.Ptr {
632 ft = ft.Elem()
633 }
634 }
635 if isStruct = ft.Kind() == reflect.Struct; !isStruct {
636 if c.converter(ft) == nil && getBuiltinConverter(ft.Kind()) == nil {
637 // Type is not supported.
638 return nil
639 }
640 }
641
642 // Reuse the unmarshaler facts when the successive type unwrappings land
643 // on the same type (the common non-pointer, non-slice case).
644 derefT := indirectType(field.Type)
645 derefU := m
646 if derefT != field.Type {
647 derefU = isTextUnmarshaler(reflect.Zero(derefT))
648 }
649 elemU := derefU
650 if ft != derefT {
651 elemU = isTextUnmarshaler(reflect.Zero(ft))
652 }
653
654 // Non-pointer builtin scalars without unmarshalers or custom converters
655 // can skip decode's dispatch entirely; converter registration resets the
656 // cache, so this build-time decision stays valid.
657 fastKind := reflect.Invalid
658 if k := field.Type.Kind(); k != reflect.Ptr && !m.IsValid &&
659 getBuiltinConverter(k) != nil && c.converter(field.Type) == nil {
660 fastKind = k
661 }
662
663 f := &fieldInfo{
664 typ: field.Type,
665 fastKind: fastKind,
666 name: field.Name,
667 alias: alias,
668 aliasLower: utilstrings.ToLower(alias),
669 canonicalAlias: canonicalAlias,
670 canonicalDot: canonicalAlias + ".",
671 unmarshalerInfo: m,
672 derefUnmarshaler: derefU,
673 elemUnmarshaler: elemU,
674 isMultipart: isMultipartField(field.Type),
675 isSliceOfStructs: isSlice && isStruct,
676 isAnonymous: field.Anonymous,
677 isRequired: options.Contains("required"),
678 defaultValue: options.getDefaultOptionValue(),
679 }
680 f.resolveDefault()
681 return f
682 }
683
684 // converter returns the converter for a type.
685 func (c *cache) converter(t reflect.Type) Converter {
686 reg := c.regconv.Load()
687 if reg == nil {
688 return nil
689 }
690 return (*reg)[t]
691 }
692
693 // ----------------------------------------------------------------------------
694
695 type structInfo struct {
696 fields []*fieldInfo
697 fieldsByName map[string]*fieldInfo
698 anonymousPtrFields []int
699 // requiredGroups lists the required keys in a stable order, so each has
700 // an index the satisfied-group bitset can address; requiredPrefixes maps
701 // a nested-key prefix to the groups a key under it can satisfy.
702 requiredGroups []requiredGroup
703 requiredPrefixes map[string][]requiredPrefix
704 // direct maps lowercase statically-resolvable keys to their precomputed
705 // parsed paths; built once and immutable, see buildDirectPaths.
706 direct map[string][]pathPart
707 // directIndex is direct, indexed for parsePathInfo's case-insensitive
708 // lookups
709 directIndex foldIndex
710 // paths caches parsed paths rooted at this struct type; keys are cloned
711 // so they never alias reused request buffers.
712 paths pathCache
713 // hasIndexedSlice reports whether any field's paths carry a slice element
714 // index, and so may grow that slice while decoding.
715 hasIndexedSlice bool
716 // defaultFields are the fields the setDefaults walk has to visit: those
717 // with a default, and the structs and pointers to structs it descends
718 // into. The rest of the fields can never be affected by it.
719 defaultFields []*fieldInfo
720 // needsDefaultsWalk reports whether the setDefaults walk can have any
721 // effect on this struct tree: it is set when a default tag option or an
722 // anonymous embedded pointer field (which the walk allocates) exists
723 // anywhere in the tree, letting the decoder skip the walk otherwise.
724 needsDefaultsWalk bool
725 }
726
727 func (i *structInfo) get(alias string) *fieldInfo {
728 // fieldsByName is keyed by lowercase alias, so the raw probe settles an
729 // already-lowercase one without folding. A mixed-case alias is folded
730 // into a stack buffer and probed from there: the compiler elides the
731 // string conversion in a map index, so that allocates nothing either.
732 if field, ok := i.fieldsByName[alias]; ok {
733 return field
734 }
735 if n := len(alias); n <= maxDirectKeyLen {
736 var buf [maxDirectKeyLen]byte
737 if !foldASCIILower(buf[:], alias) {
738 return nil // already lowercase: the probe above was conclusive
739 }
740 return i.fieldsByName[string(buf[:n])]
741 }
742 return i.fieldsByName[utilstrings.ToLower(alias)]
743 }
744
745 func (c *cache) buildRequiredFields(info *structInfo) []requiredGroup {
746 var groups []requiredGroup
747 var byKey map[string]int
748 add := func(key string, f fieldWithPrefix) {
749 if i, ok := byKey[key]; ok {
750 groups[i].fields = append(groups[i].fields, f)
751 return
752 }
753 if byKey == nil {
754 byKey = make(map[string]int)
755 }
756 byKey[key] = len(groups)
757 groups = append(groups, requiredGroup{key: key, fields: []fieldWithPrefix{f}})
758 }
759 for _, field := range info.fields {
760 if field.typ.Kind() == reflect.Struct {
761 nested := c.get(field.typ)
762 for _, prefix := range field.paths("") {
763 nestedPrefix := prefix + "."
764 for _, group := range nested.requiredGroups {
765 requiredKey := field.canonicalAlias + "." + group.key
766 for _, nestedField := range group.fields {
767 add(requiredKey, newFieldWithPrefix(nestedField.fieldInfo, nestedPrefix+nestedField.prefix))
768 }
769 }
770 }
771 }
772 if field.isRequired {
773 add(field.canonicalAlias, newFieldWithPrefix(field, ""))
774 }
775 }
776 return groups
777 }
778
779 // buildRequiredPrefixes indexes the groups by the nested-key prefix that can
780 // satisfy them ("d." for required key "d"), so a source key can be resolved
781 // against all of them at once.
782 func buildRequiredPrefixes(groups []requiredGroup) map[string][]requiredPrefix {
783 if len(groups) == 0 {
784 return nil
785 }
786 prefixes := make(map[string][]requiredPrefix)
787 for gi := range groups {
788 for _, f := range groups[gi].fields {
789 for _, dot := range f.searchPathDots {
790 owners := prefixes[dot]
791 // One entry per (group, type): several fields of a group
792 // can reach the same prefix.
793 dup := false
794 for _, o := range owners {
795 if o.group == gi && o.typ == f.typ {
796 dup = true
797 break
798 }
799 }
800 if !dup {
801 prefixes[dot] = append(owners, requiredPrefix{group: gi, typ: f.typ})
802 }
803 }
804 }
805 }
806 return prefixes
807 }
808
809 func containsAlias(infos []*structInfo, alias string) bool {
810 aliasKey := utilstrings.ToLower(alias)
811 for _, info := range infos {
812 if _, ok := info.fieldsByName[aliasKey]; ok {
813 return true
814 }
815 }
816 return false
817 }
818
819 type fieldInfo struct {
820 typ reflect.Type
821 // fastKind is the field's builtin scalar kind when decode can set it
822 // directly (no pointer, unmarshaler, or custom converter); else Invalid.
823 fastKind reflect.Kind
824 // index is the field index chain relative to the struct type whose
825 // structInfo holds this fieldInfo; promoted fields carry the full chain
826 // through the embedded structs (a copy is made per promotion level).
827 index []int
828 // name is the field name in the struct.
829 name string
830 alias string
831 // aliasLower is the pre-computed lowercase alias for fast lookups.
832 aliasLower string
833 // canonicalAlias is almost the same as the alias, but is prefixed with
834 // an embedded struct field alias in dotted notation if this field is
835 // promoted from the struct.
836 // For instance, if the alias is "N" and this field is an embedded field
837 // in a struct "X", canonicalAlias will be "X.N".
838 canonicalAlias string
839 // unmarshalerInfo contains information regarding the
840 // encoding.TextUnmarshaler implementation of the field type.
841 unmarshalerInfo unmarshaler
842 // derefUnmarshaler caches the encoding.TextUnmarshaler information for
843 // the field type after one pointer dereference, which is what the
844 // decoder sees after walking to the field. Only the type-level flags are
845 // meaningful; the decoder binds instances to live values itself.
846 derefUnmarshaler unmarshaler
847 // elemUnmarshaler is like derefUnmarshaler but for the fully unwrapped
848 // slice element type; the decoder uses it when a path terminates at a
849 // slice index (e.g. "a.0") and the value at hand is an element rather
850 // than the slice field itself.
851 elemUnmarshaler unmarshaler
852 // isMultipart indicates whether the field type is one of the supported
853 // multipart file header shapes, precomputed so the decoder can skip the
854 // type comparisons on every other field.
855 isMultipart bool
856 // isSliceOfStructs indicates if the field type is a slice of structs.
857 isSliceOfStructs bool
858 // isAnonymous indicates whether the field is embedded in the struct.
859 isAnonymous bool
860 isRequired bool
861 defaultValue string
862 // canonicalDot is canonicalAlias with the trailing separator, the prefix
863 // the fields of a nested struct are looked up under.
864 canonicalDot string
865 // def is the default option resolved at build time, nil for the fields
866 // that have none; see resolveDefault.
867 def *fieldDefault
868 }
869
870 // fieldDefault is what setDefaults assigns for a field's default option:
871 // val for a scalar field (converted to the field type) or a pointer field
872 // (converted to the pointee type), and slice, a template a slice field's
873 // default is copied from. An element that failed to convert leaves the
874 // template short and sets err, which is reported each time the default
875 // applies. A kind that takes no default leaves all three unset.
876 type fieldDefault struct {
877 val reflect.Value
878 slice reflect.Value
879 err error
880 }
881
882 func (f *fieldInfo) paths(prefix string) []string {
883 if f.alias == f.canonicalAlias {
884 return []string{prefix + f.alias}
885 }
886 return []string{prefix + f.alias, prefix + f.canonicalAlias}
887 }
888
889 type pathPart struct {
890 field *fieldInfo
891 hops []pathHop // path to the field: walks structs using field indices.
892 index int // struct index in slices of structs.
893 // soleIndex is the single struct field index hops walks, or -1; see
894 // soleHopIndex.
895 soleIndex int
896 // elem marks a terminal part whose path ended at a slice index ("a.0"):
897 // the decoder's value is then an element of the slice field rather than
898 // the field itself.
899 elem bool
900 }
901
902 // soleHopIndex returns the single struct field index hops walks, or -1 when
903 // the walk needs decode's general loop: several hops, a promoted field's
904 // index chain, or embedded pointers to allocate on the way.
905 func soleHopIndex(hops []pathHop) int {
906 if len(hops) != 1 || len(hops[0].ensure) != 0 || len(hops[0].index) != 1 {
907 return -1
908 }
909 return hops[0].index[0]
910 }
911
912 // pathHop describes one named-field lookup along a path. index is the field
913 // index chain relative to the struct at this level (more than one element
914 // when the field is promoted from embedded structs), and ensure lists the
915 // anonymous pointer fields of that struct which must be allocated before the
916 // walk so promoted fields stay reachable.
917 type pathHop struct {
918 index []int
919 ensure []int
920 }
921
922 // ----------------------------------------------------------------------------
923
924 func indirectType(typ reflect.Type) reflect.Type {
925 if typ.Kind() == reflect.Ptr {
926 return typ.Elem()
927 }
928 return typ
929 }
930
931 // fieldAlias parses a field tag to get a field alias.
932 func fieldAlias(field reflect.StructField, tagName string) (alias string, options tagOptions) {
933 if tag := field.Tag.Get(tagName); tag != "" {
934 alias, options = parseTag(tag)
935 }
936 if alias == "" {
937 alias = field.Name
938 }
939 return alias, options
940 }
941
942 // tagOptions is the string following a comma in a struct field's tag, or
943 // the empty string. It does not include the leading comma. Keeping the raw
944 // comma-separated string avoids the []string allocation of strings.Split on
945 // hot paths (the encoder parses tags on every Encode call).
946 type tagOptions string
947
948 // parseTag splits a struct field's url tag into its name and comma-separated
949 // options.
950 func parseTag(tag string) (string, tagOptions) {
951 if idx := strings.IndexByte(tag, ','); idx != -1 {
952 return tag[:idx], tagOptions(tag[idx+1:])
953 }
954 return tag, ""
955 }
956
957 // Contains checks whether the tagOptions contains the specified option.
958 func (o tagOptions) Contains(option string) bool {
959 if o == "" {
960 return false
961 }
962 for s := range strings.SplitSeq(string(o), ",") {
963 if s == option {
964 return true
965 }
966 }
967 return false
968 }
969
970 func (o tagOptions) getDefaultOptionValue() string {
971 if o == "" {
972 return ""
973 }
974 for s := range strings.SplitSeq(string(o), ",") {
975 if value, ok := strings.CutPrefix(s, "default:"); ok {
976 return value
977 }
978 }
979 return ""
980 }
981
982 // foldIndex is a read-only open-addressing index from lowercase keys to their
983 // parsed paths that is probed ASCII case-insensitively. A key's slot comes from
984 // a hash of its case-folded bytes and is confirmed with utils.EqualFold, so a
985 // mixed-case key, a header name say, costs one probe where a map needed a
986 // probe with the key as given and another with it folded, and a key naming no
987 // field is turned away just as fast.
988 type foldIndex struct {
989 // slots is a power of two long, at most half full, so every probe
990 // reaches a free slot
991 slots []foldSlot
992 mask uint64
993 len int
994 }
995
996 type foldSlot struct {
997 key string // lowercase key; "" marks a free slot, since no path is empty
998 parts []pathPart
999 }
1000
1001 // newFoldIndex indexes paths, whose keys are lowercase and non-empty.
1002 func newFoldIndex(paths map[string][]pathPart) foldIndex {
1003 if len(paths) == 0 {
1004 return foldIndex{}
1005 }
1006 size := 8
1007 for size < 2*len(paths) {
1008 size *= 2
1009 }
1010 x := foldIndex{slots: make([]foldSlot, size), mask: uint64(size - 1), len: len(paths)}
1011 for key, parts := range paths {
1012 i := utils.HashFold(key) & x.mask
1013 for x.slots[i].key != "" {
1014 i = (i + 1) & x.mask
1015 }
1016 x.slots[i] = foldSlot{key: key, parts: parts}
1017 }
1018 return x
1019 }
1020
1021 // lookup returns the parts of the key that equals k ASCII case-insensitively.
1022 func (x *foldIndex) lookup(k string) ([]pathPart, bool) {
1023 for i := utils.HashFold(k) & x.mask; ; i = (i + 1) & x.mask {
1024 s := &x.slots[i]
1025 if s.key == "" {
1026 return nil, false
1027 }
1028 if len(s.key) == len(k) && utils.EqualFold(s.key, k) {
1029 return s.parts, true
1030 }
1031 }
1032 }