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