Debian Codegraph @

cache.go

raw symbols SCIP
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
15 utils "github.com/gofiber/utils/v2"
16 utilstrings "github.com/gofiber/utils/v2/strings"
17 "github.com/gofiber/utils/v2/swar"
18 )
19
20 const maxParserIndex = 1000
21
22 // maxDirectKeyLen bounds the stack buffer used to case-fold keys probed
23 // against the direct-path map; longer keys take the generic path.
24 const maxDirectKeyLen = 64
25
26 // maxDirectPaths caps the nested entries precomputed per struct type: deep
27 // fan-out nesting multiplies dotted chains, and without a cap build time and
28 // retained memory grow exponentially. Excess keys use the generic parser.
29 const maxDirectPaths = 512
30
31 var (
32 errInvalidPath = errors.New("schema: invalid path")
33 errIndexTooLarge = errors.New("schema: index exceeds parser limit")
34 )
35
36 // newCache returns a new cache.
37 func newCache() *cache {
38 c := cache{
39 tag: "schema",
40 }
41 return &c
42 }
43
44 // cache caches meta-data about a struct.
45 type cache struct {
46 l sync.RWMutex // serializes configuration writes (tag, regconv)
47 m sync.Map // map[reflect.Type]cacheEntry
48 // regconv holds the registered converters as an immutable map published
49 // atomically: registerConverter replaces the whole map (copy-on-write
50 // under l), so readers never touch a map that is being written.
51 regconv atomic.Pointer[map[reflect.Type]Converter]
52 tag string
53 // gen is bumped (under l) before m is cleared on configuration changes;
54 // cached entries are tagged with the generation they were built under
55 // and ignored on mismatch, so any call starting after a reconfiguration
56 // returns observes the new configuration even if a racing build stored
57 // a stale entry after the clear.
58 gen atomic.Uint64
59 }
60
61 // cacheEntry tags a structInfo with the configuration generation it was
62 // built under; entries are stored by pointer in c.m (matching the encoder's
63 // encPlan pattern).
64 type cacheEntry struct {
65 info *structInfo
66 gen uint64
67 }
68
69 // registerConverter registers a converter function for a custom type.
70 func (c *cache) registerConverter(value interface{}, converterFunc Converter) {
71 c.l.Lock()
72 next := make(map[reflect.Type]Converter)
73 if prev := c.regconv.Load(); prev != nil {
74 maps.Copy(next, *prev)
75 }
76 next[reflect.TypeOf(value)] = converterFunc
77 c.regconv.Store(&next)
78 c.reset()
79 c.l.Unlock()
80 }
81
82 // parsePath parses a path in dotted notation verifying that it is a valid
83 // path to a struct field.
84 //
85 // It returns "path parts" which contain indices to fields to be used by
86 // reflect.Value.FieldByString(). Multiple parts are required for slices of
87 // structs.
88 func (c *cache) parsePath(p string, t reflect.Type) ([]pathPart, error) {
89 if t.Kind() != reflect.Struct {
90 return nil, errInvalidPath
91 }
92 return c.parsePathInfo(p, c.get(t))
93 }
94
95 // parsePathInfo is parsePath with the root struct's info already resolved,
96 // letting Decode look it up once per call instead of once per key. The
97 // parsed-path cache lives on that structInfo, keyed by the plain path
98 // string, which hashes much cheaper than a composite key.
99 func (c *cache) parsePathInfo(p string, rootInfo *structInfo) ([]pathPart, error) {
100 // Fast path: probe the precomputed direct-path map with the raw key
101 // (keys are usually already lowercase); on a miss, case-fold the key
102 // word-at-a-time (SWAR) into a stack buffer and probe once more.
103 if len(rootInfo.direct) > 0 {
104 if parts, ok := rootInfo.direct[p]; ok {
105 return parts, nil
106 }
107 if n := len(p); n <= maxDirectKeyLen {
108 var buf [maxDirectKeyLen]byte
109 changed := false
110 i := 0
111 for ; i+swar.WordLen <= n; i += swar.WordLen {
112 w := swar.Load8(p, i)
113 lw := swar.ToLowerWord(w)
114 changed = changed || lw != w
115 swar.Store8(buf[:], i, lw)
116 }
117 for ; i < n; i++ {
118 ch := p[i]
119 if ch >= 'A' && ch <= 'Z' {
120 ch += 'a' - 'A'
121 changed = true
122 }
123 buf[i] = ch
124 }
125 if changed {
126 if parts, ok := rootInfo.direct[string(buf[:n])]; ok {
127 return parts, nil
128 }
129 }
130 }
131 }
132
133 if cached, ok := rootInfo.paths.Load(p); ok {
134 return cached.([]pathPart), nil
135 }
136
137 struc := rootInfo
138 var t reflect.Type
139 var field *fieldInfo
140 var index64 int64
141 var parts []pathPart
142 var hops []pathHop
143 for keyStart := 0; ; {
144 keyEnd, segment, err := nextPathSegment(p, keyStart)
145 if err != nil {
146 return nil, errInvalidPath
147 }
148 if field = struc.get(segment); field == nil {
149 return nil, errInvalidPath
150 }
151 // Valid field. Append the hop; the field's index chain was resolved
152 // when the structInfo was built, so the decoder walks plain indices
153 // instead of repeating FieldByName lookups on every Decode call.
154 hops = append(hops, pathHop{index: field.index, ensure: struc.anonymousPtrFields})
155 if field.isSliceOfStructs && !field.isMultipart && (!field.unmarshalerInfo.IsValid || (field.unmarshalerInfo.IsValid && field.unmarshalerInfo.IsSliceElement)) {
156 // Parse a special case: slices of structs.
157 // i+1 must be the slice index.
158 //
159 // Now that struct can implements TextUnmarshaler interface,
160 // we don't need to force the struct's fields to appear in the path.
161 // So checking i+2 is not necessary anymore.
162 // We can skip this part if the type is multipart.FileHeader. It is another special case too.
163 keyStart = keyEnd + 1
164 if keyStart >= len(p) {
165 return nil, errInvalidPath
166 }
167 keyEnd, segment, err = nextPathSegment(p, keyStart)
168 if err != nil {
169 return nil, errInvalidPath
170 }
171 if index64, err = utils.ParseInt(segment); err != nil {
172 return nil, errInvalidPath
173 }
174 if index64 > maxParserIndex {
175 return nil, errIndexTooLarge
176 }
177 parts = append(parts, pathPart{
178 hops: hops,
179 field: field,
180 index: int(index64),
181 })
182 hops = nil
183
184 // Get the next struct type, dropping ptrs.
185 if field.typ.Kind() == reflect.Ptr {
186 t = field.typ.Elem()
187 } else {
188 t = field.typ
189 }
190 if t.Kind() == reflect.Slice {
191 t = t.Elem()
192 if t.Kind() == reflect.Ptr {
193 t = t.Elem()
194 }
195 }
196 } else if field.typ.Kind() == reflect.Ptr {
197 t = field.typ.Elem()
198 } else {
199 t = field.typ
200 }
201
202 if keyEnd == len(p) {
203 break
204 }
205 keyStart = keyEnd + 1
206 if keyStart >= len(p) {
207 return nil, errInvalidPath
208 }
209 if t.Kind() != reflect.Struct {
210 return nil, errInvalidPath
211 }
212 struc = c.get(t)
213 }
214 // Add the remaining. A part without hops means the path terminated at a
215 // slice index ("a.0"), so the decoder receives a slice element there.
216 parts = append(parts, pathPart{
217 hops: hops,
218 field: field,
219 index: -1,
220 elem: len(hops) == 0,
221 })
222
223 // Detach the key: callers may pass strings aliasing reused request buffers.
224 if cached, loaded := rootInfo.paths.LoadOrStore(strings.Clone(p), parts); loaded {
225 return cached.([]pathPart), nil
226 }
227
228 return parts, nil
229 }
230
231 // dotBroadcast is the SWAR needle for '.'; hoisted so the word loop in
232 // nextPathSegment pays no per-call broadcast cost.
233 var dotBroadcast = swar.Broadcast('.')
234
235 func nextPathSegment(path string, start int) (int, string, error) {
236 end := start
237 for end+swar.WordLen <= len(path) {
238 if m := swar.ZeroLanes(swar.Load8(path, end) ^ dotBroadcast); m != 0 {
239 end += swar.FirstLane(m)
240 if start == end {
241 return 0, "", errInvalidPath
242 }
243 return end, path[start:end], nil
244 }
245 end += swar.WordLen
246 }
247 for end < len(path) && path[end] != '.' {
248 end++
249 }
250 if start == end {
251 return 0, "", errInvalidPath
252 }
253 return end, path[start:end], nil
254 }
255
256 // get returns a cached structInfo, creating it if necessary.
257 func (c *cache) get(t reflect.Type) *structInfo {
258 gen := c.gen.Load()
259 if v, ok := c.m.Load(t); ok {
260 // Ignore entries built under an older configuration: a build racing
261 // a reconfiguration may store one after the clear. Hit-validation
262 // guarantees that any call starting after the reconfiguration
263 // returned observes the new configuration (a call already in flight
264 // during the reconfiguration may still briefly use old metadata,
265 // which is inherent to concurrent reconfiguration).
266 if e := v.(*cacheEntry); e.gen == gen {
267 return e.info
268 }
269 }
270 info := c.create(t, "")
271 if c.gen.Load() == gen {
272 c.m.Store(t, &cacheEntry{info: info, gen: gen})
273 }
274 // If the configuration changed while building, serve the result once
275 // without caching it (or with a stale tag that hit-validation ignores);
276 // the next call rebuilds fresh.
277 return info
278 }
279
280 // reset clears cached metadata and must be called with c.l held. Parsed
281 // path caches live on the structInfos, so dropping them drops those too.
282 func (c *cache) reset() {
283 c.gen.Add(1)
284 c.m.Clear()
285 }
286
287 // aliasTag returns the configured tag name under the configuration lock, so
288 // metadata builds racing SetAliasTag read a consistent value.
289 func (c *cache) aliasTag() string {
290 c.l.RLock()
291 tag := c.tag
292 c.l.RUnlock()
293 return tag
294 }
295
296 // create creates a structInfo with meta-data about a struct.
297 func (c *cache) create(t reflect.Type, parentAlias string) *structInfo {
298 // Snapshot the alias tag once so every field of this type is analyzed
299 // under a consistent configuration and we don't churn the config lock
300 // per field.
301 tag := c.aliasTag()
302 info := &structInfo{}
303 var anonymousInfos []*structInfo
304 var anonymousIdx [][]int
305 for i := 0; i < t.NumField(); i++ {
306 structField := t.Field(i)
307 // Only exported anonymous pointers can be allocated; unexported ones
308 // are not settable and Set would panic.
309 if structField.Anonymous && structField.Type.Kind() == reflect.Ptr && structField.IsExported() {
310 info.anonymousPtrFields = append(info.anonymousPtrFields, i)
311 }
312 if f := c.createField(structField, parentAlias, tag); f != nil {
313 f.index = structField.Index
314 info.fields = append(info.fields, f)
315 if ft := indirectType(f.typ); ft.Kind() == reflect.Struct && f.isAnonymous {
316 anonymousInfos = append(anonymousInfos, c.create(ft, f.canonicalAlias))
317 anonymousIdx = append(anonymousIdx, structField.Index)
318 }
319 }
320 }
321 for i, a := range anonymousInfos {
322 others := []*structInfo{info}
323 others = append(others, anonymousInfos[:i]...)
324 others = append(others, anonymousInfos[i+1:]...)
325 for _, f := range a.fields {
326 if !containsAlias(others, f.alias) {
327 // Copy the promoted field so its index chain can be prefixed
328 // with the embedded field's index; the original stays valid
329 // for the embedded type's own structInfo.
330 pf := *f
331 pf.index = append(append(make([]int, 0, len(anonymousIdx[i])+len(f.index)), anonymousIdx[i]...), f.index...)
332 info.fields = append(info.fields, &pf)
333 }
334 }
335 }
336 info.fieldsByName = make(map[string]*fieldInfo, len(info.fields))
337 for _, field := range info.fields {
338 if _, exists := info.fieldsByName[field.aliasLower]; !exists {
339 info.fieldsByName[field.aliasLower] = field
340 }
341 }
342 info.requiredFields = c.buildRequiredFields(info)
343 info.direct = c.buildDirectPaths(info)
344 // The setDefaults walk also allocates nil anonymous embedded pointers,
345 // so it can only be skipped when neither defaults nor such pointers
346 // exist anywhere in the tree.
347 info.needsDefaultsWalk = c.needsDefaultsWalk(t, tag, map[reflect.Type]bool{})
348 return info
349 }
350
351 // buildDirectPaths precomputes, keyed by lowercase path, the parsed paths for
352 // every key resolvable without runtime state: flat aliases plus dotted chains
353 // through non-pointer nested struct fields.
354 func (c *cache) buildDirectPaths(info *structInfo) map[string][]pathPart {
355 direct := make(map[string][]pathPart, len(info.fieldsByName))
356 // Flat aliases first (linear in field count) so the cap below can never
357 // crowd them out; iterate fields in declaration order, honoring
358 // fieldsByName's first-wins rule.
359 for _, f := range info.fields {
360 if !directEligible(info, f) {
361 continue
362 }
363 direct[f.aliasLower] = []pathPart{{
364 hops: []pathHop{{index: f.index, ensure: info.anonymousPtrFields}},
365 field: f,
366 index: -1,
367 }}
368 }
369 for _, f := range info.fields {
370 if len(direct) >= maxDirectPaths {
371 break
372 }
373 if !directEligible(info, f) || f.typ.Kind() != reflect.Struct {
374 continue
375 }
376 // Non-pointer struct nesting cannot recurse (the type would be
377 // illegal), so the child's info is always buildable here.
378 hop := pathHop{index: f.index, ensure: info.anonymousPtrFields}
379 for childKey, childParts := range c.get(f.typ).direct {
380 if len(direct) >= maxDirectPaths {
381 break
382 }
383 cp := childParts[0]
384 hops := make([]pathHop, 0, len(cp.hops)+1)
385 hops = append(hops, hop)
386 hops = append(hops, cp.hops...)
387 direct[f.aliasLower+"."+childKey] = []pathPart{{
388 hops: hops,
389 field: cp.field,
390 index: -1,
391 }}
392 }
393 }
394 return direct
395 }
396
397 // directEligible reports whether f can serve as a direct-path terminal: it is
398 // its alias's first-wins winner, the alias has no dot, and a bare alias is a
399 // valid path (slice-of-structs fields require a following slice index).
400 func directEligible(info *structInfo, f *fieldInfo) bool {
401 if info.fieldsByName[f.aliasLower] != f || strings.IndexByte(f.aliasLower, '.') >= 0 {
402 return false
403 }
404 needsIndex := f.isSliceOfStructs && !f.isMultipart && (!f.unmarshalerInfo.IsValid || f.unmarshalerInfo.IsSliceElement)
405 return !needsIndex
406 }
407
408 // needsDefaultsWalk reports whether the setDefaults walk can have any effect
409 // on the struct tree rooted at t: it declares a default tag option, or has an
410 // (exported) anonymous pointer field the walk allocates, anywhere in the
411 // tree. visited guards against recursive types. tag is the alias tag
412 // snapshot for this build, so no per-field config lock is taken.
413 func (c *cache) needsDefaultsWalk(t reflect.Type, tag string, visited map[reflect.Type]bool) bool {
414 if t.Kind() == reflect.Ptr {
415 t = t.Elem()
416 }
417 if t.Kind() != reflect.Struct || visited[t] {
418 return false
419 }
420 visited[t] = true
421 for i := 0; i < t.NumField(); i++ {
422 field := t.Field(i)
423 // Mirror the anonymousPtrFields filter: only exported anonymous
424 // pointers are ever allocated, so only they justify the walk.
425 if field.Anonymous && field.Type.Kind() == reflect.Ptr && field.IsExported() {
426 return true
427 }
428 alias, options := fieldAlias(field, tag)
429 if alias == "-" {
430 continue
431 }
432 if options.getDefaultOptionValue() != "" {
433 return true
434 }
435 if c.needsDefaultsWalk(field.Type, tag, visited) {
436 return true
437 }
438 }
439 return false
440 }
441
442 // createField creates a fieldInfo for the given field. tag is the alias tag
443 // snapshot for the enclosing type's build.
444 func (c *cache) createField(field reflect.StructField, parentAlias, tag string) *fieldInfo {
445 alias, options := fieldAlias(field, tag)
446 if alias == "-" {
447 // Ignore this field.
448 return nil
449 }
450 canonicalAlias := alias
451 if parentAlias != "" {
452 canonicalAlias = parentAlias + "." + alias
453 }
454 // Check if the type is supported and don't cache it if not.
455 // First let's get the basic type.
456 isSlice, isStruct := false, false
457 ft := field.Type
458 m := isTextUnmarshaler(reflect.Zero(ft))
459 if ft.Kind() == reflect.Ptr {
460 ft = ft.Elem()
461 }
462 if isSlice = ft.Kind() == reflect.Slice; isSlice {
463 ft = ft.Elem()
464 if ft.Kind() == reflect.Ptr {
465 ft = ft.Elem()
466 }
467 }
468 if ft.Kind() == reflect.Array {
469 ft = ft.Elem()
470 if ft.Kind() == reflect.Ptr {
471 ft = ft.Elem()
472 }
473 }
474 if isStruct = ft.Kind() == reflect.Struct; !isStruct {
475 if c.converter(ft) == nil && getBuiltinConverter(ft.Kind()) == nil {
476 // Type is not supported.
477 return nil
478 }
479 }
480
481 // Reuse the unmarshaler facts when the successive type unwrappings land
482 // on the same type (the common non-pointer, non-slice case).
483 derefT := indirectType(field.Type)
484 derefU := m
485 if derefT != field.Type {
486 derefU = isTextUnmarshaler(reflect.Zero(derefT))
487 }
488 elemU := derefU
489 if ft != derefT {
490 elemU = isTextUnmarshaler(reflect.Zero(ft))
491 }
492
493 // Non-pointer builtin scalars without unmarshalers or custom converters
494 // can skip decode's dispatch entirely; converter registration resets the
495 // cache, so this build-time decision stays valid.
496 fastKind := reflect.Invalid
497 if k := field.Type.Kind(); k != reflect.Ptr && !m.IsValid &&
498 getBuiltinConverter(k) != nil && c.converter(field.Type) == nil {
499 fastKind = k
500 }
501
502 return &fieldInfo{
503 typ: field.Type,
504 fastKind: fastKind,
505 name: field.Name,
506 alias: alias,
507 aliasLower: utilstrings.ToLower(alias),
508 canonicalAlias: canonicalAlias,
509 unmarshalerInfo: m,
510 derefUnmarshaler: derefU,
511 elemUnmarshaler: elemU,
512 isMultipart: isMultipartField(field.Type),
513 isSliceOfStructs: isSlice && isStruct,
514 isAnonymous: field.Anonymous,
515 isRequired: options.Contains("required"),
516 defaultValue: options.getDefaultOptionValue(),
517 }
518 }
519
520 // converter returns the converter for a type.
521 func (c *cache) converter(t reflect.Type) Converter {
522 reg := c.regconv.Load()
523 if reg == nil {
524 return nil
525 }
526 return (*reg)[t]
527 }
528
529 // ----------------------------------------------------------------------------
530
531 type structInfo struct {
532 fields []*fieldInfo
533 fieldsByName map[string]*fieldInfo
534 anonymousPtrFields []int
535 requiredFields map[string][]fieldWithPrefix
536 // direct maps lowercase statically-resolvable keys to their precomputed
537 // parsed paths; built once and immutable, see buildDirectPaths.
538 direct map[string][]pathPart
539 // paths caches parsed paths rooted at this struct type
540 // (map[string][]pathPart); keys are cloned so they never alias reused
541 // request buffers.
542 paths sync.Map
543 // needsDefaultsWalk reports whether the setDefaults walk can have any
544 // effect on this struct tree: it is set when a default tag option or an
545 // anonymous embedded pointer field (which the walk allocates) exists
546 // anywhere in the tree, letting the decoder skip the walk otherwise.
547 needsDefaultsWalk bool
548 }
549
550 func (i *structInfo) get(alias string) *fieldInfo {
551 aliasKey := utilstrings.ToLower(alias)
552 if field, ok := i.fieldsByName[aliasKey]; ok {
553 return field
554 }
555 return nil
556 }
557
558 func (c *cache) buildRequiredFields(info *structInfo) map[string][]fieldWithPrefix {
559 var requiredFields map[string][]fieldWithPrefix
560 for _, field := range info.fields {
561 if field.typ.Kind() == reflect.Struct {
562 nested := c.get(field.typ)
563 for _, prefix := range field.paths("") {
564 nestedPrefix := prefix + "."
565 for key, fields := range nested.requiredFields {
566 requiredKey := field.canonicalAlias + "." + key
567 for _, nestedField := range fields {
568 requiredFields = appendRequiredField(requiredFields, requiredKey,
569 newFieldWithPrefix(nestedField.fieldInfo, nestedPrefix+nestedField.prefix))
570 }
571 }
572 }
573 }
574 if field.isRequired {
575 requiredFields = appendRequiredField(requiredFields, field.canonicalAlias,
576 newFieldWithPrefix(field, ""))
577 }
578 }
579 return requiredFields
580 }
581
582 func containsAlias(infos []*structInfo, alias string) bool {
583 aliasKey := utilstrings.ToLower(alias)
584 for _, info := range infos {
585 if _, ok := info.fieldsByName[aliasKey]; ok {
586 return true
587 }
588 }
589 return false
590 }
591
592 type fieldInfo struct {
593 typ reflect.Type
594 // fastKind is the field's builtin scalar kind when decode can set it
595 // directly (no pointer, unmarshaler, or custom converter); else Invalid.
596 fastKind reflect.Kind
597 // index is the field index chain relative to the struct type whose
598 // structInfo holds this fieldInfo; promoted fields carry the full chain
599 // through the embedded structs (a copy is made per promotion level).
600 index []int
601 // name is the field name in the struct.
602 name string
603 alias string
604 // aliasLower is the pre-computed lowercase alias for fast lookups.
605 aliasLower string
606 // canonicalAlias is almost the same as the alias, but is prefixed with
607 // an embedded struct field alias in dotted notation if this field is
608 // promoted from the struct.
609 // For instance, if the alias is "N" and this field is an embedded field
610 // in a struct "X", canonicalAlias will be "X.N".
611 canonicalAlias string
612 // unmarshalerInfo contains information regarding the
613 // encoding.TextUnmarshaler implementation of the field type.
614 unmarshalerInfo unmarshaler
615 // derefUnmarshaler caches the encoding.TextUnmarshaler information for
616 // the field type after one pointer dereference, which is what the
617 // decoder sees after walking to the field. Only the type-level flags are
618 // meaningful; the decoder binds instances to live values itself.
619 derefUnmarshaler unmarshaler
620 // elemUnmarshaler is like derefUnmarshaler but for the fully unwrapped
621 // slice element type; the decoder uses it when a path terminates at a
622 // slice index (e.g. "a.0") and the value at hand is an element rather
623 // than the slice field itself.
624 elemUnmarshaler unmarshaler
625 // isMultipart indicates whether the field type is one of the supported
626 // multipart file header shapes, precomputed so the decoder can skip the
627 // type comparisons on every other field.
628 isMultipart bool
629 // isSliceOfStructs indicates if the field type is a slice of structs.
630 isSliceOfStructs bool
631 // isAnonymous indicates whether the field is embedded in the struct.
632 isAnonymous bool
633 isRequired bool
634 defaultValue string
635 }
636
637 func (f *fieldInfo) paths(prefix string) []string {
638 if f.alias == f.canonicalAlias {
639 return []string{prefix + f.alias}
640 }
641 return []string{prefix + f.alias, prefix + f.canonicalAlias}
642 }
643
644 type pathPart struct {
645 field *fieldInfo
646 hops []pathHop // path to the field: walks structs using field indices.
647 index int // struct index in slices of structs.
648 // elem marks a terminal part whose path ended at a slice index ("a.0"):
649 // the decoder's value is then an element of the slice field rather than
650 // the field itself.
651 elem bool
652 }
653
654 // pathHop describes one named-field lookup along a path. index is the field
655 // index chain relative to the struct at this level (more than one element
656 // when the field is promoted from embedded structs), and ensure lists the
657 // anonymous pointer fields of that struct which must be allocated before the
658 // walk so promoted fields stay reachable.
659 type pathHop struct {
660 index []int
661 ensure []int
662 }
663
664 // ----------------------------------------------------------------------------
665
666 func indirectType(typ reflect.Type) reflect.Type {
667 if typ.Kind() == reflect.Ptr {
668 return typ.Elem()
669 }
670 return typ
671 }
672
673 // fieldAlias parses a field tag to get a field alias.
674 func fieldAlias(field reflect.StructField, tagName string) (alias string, options tagOptions) {
675 if tag := field.Tag.Get(tagName); tag != "" {
676 alias, options = parseTag(tag)
677 }
678 if alias == "" {
679 alias = field.Name
680 }
681 return alias, options
682 }
683
684 // tagOptions is the string following a comma in a struct field's tag, or
685 // the empty string. It does not include the leading comma. Keeping the raw
686 // comma-separated string avoids the []string allocation of strings.Split on
687 // hot paths (the encoder parses tags on every Encode call).
688 type tagOptions string
689
690 // parseTag splits a struct field's url tag into its name and comma-separated
691 // options.
692 func parseTag(tag string) (string, tagOptions) {
693 if idx := strings.IndexByte(tag, ','); idx != -1 {
694 return tag[:idx], tagOptions(tag[idx+1:])
695 }
696 return tag, ""
697 }
698
699 // Contains checks whether the tagOptions contains the specified option.
700 func (o tagOptions) Contains(option string) bool {
701 if o == "" {
702 return false
703 }
704 for s := range strings.SplitSeq(string(o), ",") {
705 if s == option {
706 return true
707 }
708 }
709 return false
710 }
711
712 func (o tagOptions) getDefaultOptionValue() string {
713 if o == "" {
714 return ""
715 }
716 for s := range strings.SplitSeq(string(o), ",") {
717 if value, ok := strings.CutPrefix(s, "default:"); ok {
718 return value
719 }
720 }
721 return ""
722 }