| 1 | // Copyright 2012 The Gorilla Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package schema |
| 6 | |
| 7 | import ( |
| 8 | "encoding" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "maps" |
| 12 | "mime/multipart" |
| 13 | "reflect" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | ) |
| 17 | |
| 18 | const ( |
| 19 | defaultMaxSize = 16000 |
| 20 | ) |
| 21 | |
| 22 | // errNotPointerToStruct is returned by Decode for invalid destinations; |
| 23 | // hoisted so the check does not allocate on every call. |
| 24 | var errNotPointerToStruct = errors.New("schema: interface must be a pointer to struct") |
| 25 | |
| 26 | var decodeValueBufferPool = sync.Pool{ |
| 27 | New: func() any { |
| 28 | buf := make([]reflect.Value, 0, 8) |
| 29 | return &buf |
| 30 | }, |
| 31 | } |
| 32 | |
| 33 | // NewDecoder returns a new Decoder. |
| 34 | func NewDecoder() *Decoder { |
| 35 | return &Decoder{cache: newCache(), maxSize: defaultMaxSize} |
| 36 | } |
| 37 | |
| 38 | // Decoder decodes values from a map[string][]string to a struct. |
| 39 | type Decoder struct { |
| 40 | cache *cache |
| 41 | zeroEmpty bool |
| 42 | ignoreUnknownKeys bool |
| 43 | maxSize int |
| 44 | } |
| 45 | |
| 46 | // SetAliasTag changes the tag used to locate custom field aliases. |
| 47 | // The default tag is "schema". |
| 48 | func (d *Decoder) SetAliasTag(tag string) { |
| 49 | d.cache.l.Lock() |
| 50 | d.cache.tag = tag |
| 51 | d.cache.reset() |
| 52 | d.cache.l.Unlock() |
| 53 | } |
| 54 | |
| 55 | // ZeroEmpty controls the behaviour when the decoder encounters empty values |
| 56 | // in a map. |
| 57 | // If z is true and a key in the map has the empty string as a value |
| 58 | // then the corresponding struct field is set to the zero value. |
| 59 | // If z is false then empty strings are ignored. |
| 60 | // |
| 61 | // The default value is false, that is empty values do not change |
| 62 | // the value of the struct field. |
| 63 | func (d *Decoder) ZeroEmpty(z bool) { |
| 64 | d.zeroEmpty = z |
| 65 | } |
| 66 | |
| 67 | // IgnoreUnknownKeys controls the behaviour when the decoder encounters unknown |
| 68 | // keys in the map. |
| 69 | // If i is true and an unknown field is encountered, it is ignored. This is |
| 70 | // similar to how unknown keys are handled by encoding/json. |
| 71 | // If i is false then Decode will return an error. Note that any valid keys |
| 72 | // will still be decoded in to the target struct. |
| 73 | // |
| 74 | // To preserve backwards compatibility, the default value is false. |
| 75 | func (d *Decoder) IgnoreUnknownKeys(i bool) { |
| 76 | d.ignoreUnknownKeys = i |
| 77 | } |
| 78 | |
| 79 | // MaxSize limits the size of slices for URL nested arrays or object arrays. |
| 80 | // Choose MaxSize carefully; large values may create many zero-value slice elements. |
| 81 | // Example: "items.100000=apple" would create a slice with 100,000 empty strings. |
| 82 | func (d *Decoder) MaxSize(size int) { |
| 83 | d.maxSize = size |
| 84 | } |
| 85 | |
| 86 | // RegisterConverter registers a converter function for a custom type. |
| 87 | func (d *Decoder) RegisterConverter(value interface{}, converterFunc Converter) { |
| 88 | d.cache.registerConverter(value, converterFunc) |
| 89 | } |
| 90 | |
| 91 | // Decode decodes a map[string][]string to a struct. |
| 92 | // |
| 93 | // The first parameter must be a pointer to a struct. |
| 94 | // |
| 95 | // The second parameter is a map, typically url.Values from an HTTP request. |
| 96 | // Keys are "paths" in dotted notation to the struct fields and nested structs. |
| 97 | // |
| 98 | // See the package documentation for a full explanation of the mechanics. |
| 99 | func (d *Decoder) Decode(dst interface{}, src map[string][]string, files ...map[string][]*multipart.FileHeader) (err error) { |
| 100 | v := reflect.ValueOf(dst) |
| 101 | if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { |
| 102 | return errNotPointerToStruct |
| 103 | } |
| 104 | |
| 105 | // Catch panics from the decoder and return them as an error. |
| 106 | // This is needed because the decoder calls reflect and reflect panics. |
| 107 | // Installed before any other work so nothing can crash the caller. |
| 108 | defer func() { |
| 109 | if r := recover(); r != nil { |
| 110 | if e, ok := r.(error); ok { |
| 111 | err = e |
| 112 | } else { |
| 113 | err = fmt.Errorf("schema: panic while decoding: %v", r) |
| 114 | } |
| 115 | } |
| 116 | }() |
| 117 | |
| 118 | var multipartFiles map[string][]*multipart.FileHeader |
| 119 | |
| 120 | if len(files) > 0 { |
| 121 | multipartFiles = files[0] |
| 122 | } |
| 123 | |
| 124 | // Add files as empty string values to the decode view so path parsing |
| 125 | // works uniformly. Work on a copy: the caller's src map must not be |
| 126 | // mutated (and a caller-provided value under a file's key must not be |
| 127 | // overwritten in it). |
| 128 | if len(multipartFiles) > 0 { |
| 129 | merged := make(map[string][]string, len(src)+len(multipartFiles)) |
| 130 | maps.Copy(merged, src) |
| 131 | for path := range multipartFiles { |
| 132 | merged[path] = []string{""} |
| 133 | } |
| 134 | src = merged |
| 135 | } |
| 136 | |
| 137 | v = v.Elem() |
| 138 | t := v.Type() |
| 139 | rootInfo := d.cache.get(t) |
| 140 | var multiErrors MultiError |
| 141 | for path, values := range src { |
| 142 | if parts, err := d.cache.parsePathInfo(path, rootInfo); err == nil { |
| 143 | var filesSlice []*multipart.FileHeader |
| 144 | if multipartFiles != nil { |
| 145 | filesSlice = multipartFiles[path] |
| 146 | } |
| 147 | if err = d.decode(v, path, parts, values, filesSlice); err != nil { |
| 148 | multiErrors = appendError(multiErrors, path, err) |
| 149 | } |
| 150 | } else { |
| 151 | if errors.Is(err, errIndexTooLarge) { |
| 152 | multiErrors = appendError(multiErrors, path, err) |
| 153 | } else if !d.ignoreUnknownKeys { |
| 154 | multiErrors = appendError(multiErrors, path, UnknownKeyError{Key: path}) |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | if rootInfo.needsDefaultsWalk { |
| 159 | multiErrors = mergeErrors(multiErrors, d.setDefaults(t, v, src, "")) |
| 160 | } |
| 161 | multiErrors = mergeErrors(multiErrors, d.checkRequired(rootInfo, src)) |
| 162 | if len(multiErrors) > 0 { |
| 163 | return multiErrors |
| 164 | } |
| 165 | return nil |
| 166 | } |
| 167 | |
| 168 | // setDefaults sets the default values when the `default` tag is specified, |
| 169 | // default is supported on basic/primitive types and their pointers, |
| 170 | // nested structs can also have default tags |
| 171 | func (d *Decoder) setDefaults(t reflect.Type, v reflect.Value, src map[string][]string, prefix string) MultiError { |
| 172 | struc := d.cache.get(t) |
| 173 | // Skip the walk entirely when it can have no effect (no default tags and |
| 174 | // no anonymous embedded pointers to allocate anywhere in the tree) — the |
| 175 | // overwhelmingly common case. |
| 176 | if !struc.needsDefaultsWalk { |
| 177 | return nil |
| 178 | } |
| 179 | |
| 180 | var errs MultiError |
| 181 | |
| 182 | // Allocate nil anonymous embedded pointer fields so their promoted |
| 183 | // fields stay reachable. |
| 184 | for _, idx := range struc.anonymousPtrFields { |
| 185 | if field := v.Field(idx); field.IsNil() { |
| 186 | field.Set(reflect.New(field.Type().Elem())) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | for _, f := range struc.fields { |
| 191 | vCurrent := walkIndexChain(v, f.index) |
| 192 | if !vCurrent.IsValid() { |
| 193 | // Unreachable behind an unsettable nil embedded pointer. |
| 194 | continue |
| 195 | } |
| 196 | |
| 197 | if vCurrent.Type().Kind() == reflect.Struct && f.defaultValue == "" { |
| 198 | errs = mergeErrors(errs, d.setDefaults(vCurrent.Type(), vCurrent, src, prefix+f.canonicalAlias+".")) |
| 199 | } else if isPointerToStruct(vCurrent) && f.defaultValue == "" { |
| 200 | errs = mergeErrors(errs, d.setDefaults(vCurrent.Elem().Type(), vCurrent.Elem(), src, prefix+f.canonicalAlias+".")) |
| 201 | } |
| 202 | |
| 203 | if f.defaultValue != "" && f.isRequired { |
| 204 | errs = appendError(errs, "default-"+f.name, errors.New("required fields cannot have a default value")) |
| 205 | } else if f.defaultValue != "" && vCurrent.IsZero() && !f.isRequired && !fieldProvided(src, prefix, f) { |
| 206 | if f.typ.Kind() == reflect.Struct { |
| 207 | errs = appendError(errs, "default-"+f.name, errors.New("default option is supported only on: bool, float variants, string, unit variants types or their corresponding pointers or slices")) |
| 208 | } else if f.typ.Kind() == reflect.Slice { |
| 209 | // check if slice has one of the supported types for defaults |
| 210 | conv := getBuiltinConverter(f.typ.Elem().Kind()) |
| 211 | if conv == nil { |
| 212 | errs = appendError(errs, "default-"+f.name, errors.New("default option is supported only on: bool, float variants, string, unit variants types or their corresponding pointers or slices")) |
| 213 | continue |
| 214 | } |
| 215 | |
| 216 | elemT := f.typ.Elem() |
| 217 | defaultSlice := reflect.MakeSlice(f.typ, 0, strings.Count(f.defaultValue, "|")+1) |
| 218 | for val := range strings.SplitSeq(f.defaultValue, "|") { |
| 219 | // this check is to handle if the wrong value is provided |
| 220 | convertedVal := conv(val) |
| 221 | if !convertedVal.IsValid() { |
| 222 | errs = appendError(errs, "default-"+f.name, fmt.Errorf("failed setting default: %s is not compatible with field %s type", val, f.name)) |
| 223 | break |
| 224 | } |
| 225 | // Builtin converters return the underlying kind; convert to |
| 226 | // the (possibly named) element type before appending, else |
| 227 | // reflect.Append panics for e.g. []MyInt. |
| 228 | defaultSlice = reflect.Append(defaultSlice, convertedVal.Convert(elemT)) |
| 229 | } |
| 230 | vCurrent.Set(defaultSlice) |
| 231 | } else if f.typ.Kind() == reflect.Ptr { |
| 232 | t1 := f.typ.Elem() |
| 233 | |
| 234 | if t1.Kind() == reflect.Struct || t1.Kind() == reflect.Slice { |
| 235 | errs = appendError(errs, "default-"+f.name, errors.New("default option is supported only on: bool, float variants, string, unit variants types or their corresponding pointers or slices")) |
| 236 | } |
| 237 | |
| 238 | // this check is to handle if the wrong value is provided |
| 239 | if conv := getBuiltinConverter(t1.Kind()); conv != nil { |
| 240 | if convertedVal := conv(f.defaultValue); convertedVal.IsValid() { |
| 241 | // Build a pointer of the field's actual element type: |
| 242 | // the converter yields the underlying kind, which is |
| 243 | // convertible to the (possibly named) element type, |
| 244 | // and *elem is assignable to the field even when the |
| 245 | // field's type is itself a named pointer type (e.g. |
| 246 | // type MyIntPtr *MyInt), where converting a *int |
| 247 | // directly would panic. |
| 248 | p := reflect.New(t1) |
| 249 | p.Elem().Set(convertedVal.Convert(t1)) |
| 250 | vCurrent.Set(p) |
| 251 | } |
| 252 | } |
| 253 | } else { |
| 254 | // this check is to handle if the wrong value is provided |
| 255 | conv := getBuiltinConverter(f.typ.Kind()) |
| 256 | if conv == nil { |
| 257 | errs = appendError(errs, "default-"+f.name, errors.New("default option is supported only on: bool, float variants, string, unit variants types or their corresponding pointers or slices")) |
| 258 | } else if convertedVal := conv(f.defaultValue); convertedVal.IsValid() { |
| 259 | // Builtin converters return the underlying kind; convert to |
| 260 | // the field's (possibly named) type before assigning. |
| 261 | vCurrent.Set(convertedVal.Convert(f.typ)) |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | return errs |
| 268 | } |
| 269 | |
| 270 | func isPointerToStruct(v reflect.Value) bool { |
| 271 | return !v.IsZero() && v.Type().Kind() == reflect.Ptr && v.Elem().Type().Kind() == reflect.Struct |
| 272 | } |
| 273 | |
| 274 | func fieldProvided(src map[string][]string, prefix string, f *fieldInfo) bool { |
| 275 | for _, p := range f.paths(prefix) { |
| 276 | if _, ok := src[p]; ok { |
| 277 | return true |
| 278 | } |
| 279 | } |
| 280 | return false |
| 281 | } |
| 282 | |
| 283 | // checkRequired checks whether required fields are empty |
| 284 | // |
| 285 | // The set of required fields (including those of nested structs) is |
| 286 | // precomputed once per struct type in structInfo.requiredFields, so this |
| 287 | // only performs the per-request emptiness checks against src. |
| 288 | // |
| 289 | // src is the source map for decoding, we use it here to see if those required fields are included in src |
| 290 | func (d *Decoder) checkRequired(info *structInfo, src map[string][]string) MultiError { |
| 291 | var errs MultiError |
| 292 | for key, fields := range info.requiredFields { |
| 293 | if isEmptyFields(fields, src) { |
| 294 | errs = appendError(errs, key, EmptyFieldError{Key: key}) |
| 295 | } |
| 296 | } |
| 297 | return errs |
| 298 | } |
| 299 | |
| 300 | type fieldWithPrefix struct { |
| 301 | *fieldInfo |
| 302 | prefix string |
| 303 | // searchPaths lists the src keys this required field answers to, and |
| 304 | // searchPathDots the corresponding nested-key prefixes; both are |
| 305 | // precomputed at cache-build time so per-request checks allocate |
| 306 | // nothing. |
| 307 | searchPaths []string |
| 308 | searchPathDots []string |
| 309 | } |
| 310 | |
| 311 | func newFieldWithPrefix(f *fieldInfo, prefix string) fieldWithPrefix { |
| 312 | paths := f.paths(prefix) |
| 313 | dots := make([]string, len(paths)) |
| 314 | for i, p := range paths { |
| 315 | dots[i] = p + "." |
| 316 | } |
| 317 | return fieldWithPrefix{ |
| 318 | fieldInfo: f, |
| 319 | prefix: prefix, |
| 320 | searchPaths: paths, |
| 321 | searchPathDots: dots, |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | // isEmptyFields returns true if all of specified fields are empty. |
| 326 | func isEmptyFields(fields []fieldWithPrefix, src map[string][]string) bool { |
| 327 | for _, f := range fields { |
| 328 | for i, path := range f.searchPaths { |
| 329 | v, ok := src[path] |
| 330 | if ok && !isEmpty(f.typ, v) { |
| 331 | return false |
| 332 | } |
| 333 | // Check for nested keys that match this field. |
| 334 | pathDot := f.searchPathDots[i] |
| 335 | for key, val := range src { |
| 336 | if len(val) == 0 { |
| 337 | continue |
| 338 | } |
| 339 | // for nested structs |
| 340 | if strings.HasPrefix(key, pathDot) { |
| 341 | if !isEmpty(f.typ, val) { |
| 342 | return false |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | return true |
| 349 | } |
| 350 | |
| 351 | // isEmpty returns true if value is empty for specific type |
| 352 | func isEmpty(t reflect.Type, value []string) bool { |
| 353 | if len(value) == 0 { |
| 354 | return true |
| 355 | } |
| 356 | switch t.Kind() { |
| 357 | case boolType, float32Type, float64Type, |
| 358 | intType, int8Type, int16Type, int32Type, int64Type, |
| 359 | stringType, |
| 360 | uintType, uint8Type, uint16Type, uint32Type, uint64Type: |
| 361 | return len(value[0]) == 0 |
| 362 | } |
| 363 | return false |
| 364 | } |
| 365 | |
| 366 | var ( |
| 367 | multipartFileHeaderPointerType = reflect.TypeOf(&multipart.FileHeader{}) |
| 368 | sliceMultipartFileHeaderPointerType = reflect.TypeOf([]*multipart.FileHeader{}) |
| 369 | ) |
| 370 | |
| 371 | // Supported multiple types: |
| 372 | // *multipart.FileHeader, *[]multipart.FileHeader, []*multipart.FileHeader |
| 373 | func handleMultipartField(field reflect.Value, files []*multipart.FileHeader) bool { |
| 374 | fieldType := field.Type() |
| 375 | if !isMultipartField(fieldType) { |
| 376 | return false |
| 377 | } |
| 378 | |
| 379 | // Skip if files are empty and field is multipart |
| 380 | if len(files) == 0 { |
| 381 | return true |
| 382 | } |
| 383 | |
| 384 | // Check for *multipart.FileHeader |
| 385 | if fieldType == multipartFileHeaderPointerType { |
| 386 | field.Set(reflect.ValueOf(files[0])) |
| 387 | return true |
| 388 | } |
| 389 | |
| 390 | // Check for []*multipart.FileHeader |
| 391 | if fieldType == sliceMultipartFileHeaderPointerType { |
| 392 | field.Set(reflect.ValueOf(files)) |
| 393 | return true |
| 394 | } |
| 395 | |
| 396 | // Check for *[]*multipart.FileHeader |
| 397 | if fieldType.Kind() == reflect.Pointer { |
| 398 | fieldType = fieldType.Elem() |
| 399 | |
| 400 | if field.IsNil() { |
| 401 | field.Set(reflect.New(fieldType)) |
| 402 | } |
| 403 | |
| 404 | if fieldType == sliceMultipartFileHeaderPointerType { |
| 405 | field.Elem().Set(reflect.ValueOf(files)) |
| 406 | return true |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | return false |
| 411 | } |
| 412 | |
| 413 | // Supported multiple types: |
| 414 | // *multipart.FileHeader, *[]multipart.FileHeader, []*multipart.FileHeader |
| 415 | func isMultipartField(typ reflect.Type) bool { |
| 416 | // Check for *multipart.FileHeader |
| 417 | if typ == multipartFileHeaderPointerType { |
| 418 | return true |
| 419 | } |
| 420 | |
| 421 | // Check for []*multipart.FileHeader |
| 422 | if typ == sliceMultipartFileHeaderPointerType { |
| 423 | return true |
| 424 | } |
| 425 | |
| 426 | // Check for *[]*multipart.FileHeader |
| 427 | if typ.Kind() == reflect.Ptr { |
| 428 | typ = typ.Elem() |
| 429 | |
| 430 | if typ == sliceMultipartFileHeaderPointerType { |
| 431 | return true |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | return false |
| 436 | } |
| 437 | |
| 438 | // walkIndexChain walks v along a struct field index chain. Chains longer |
| 439 | // than one element traverse embedded structs; intermediate nil pointers are |
| 440 | // allocated so promoted fields stay reachable. It returns the zero Value |
| 441 | // when the chain is blocked by a nil pointer that cannot be set (an |
| 442 | // unexported embedded pointer), which callers treat as an unreachable |
| 443 | // field. |
| 444 | func walkIndexChain(v reflect.Value, chain []int) reflect.Value { |
| 445 | for j, fi := range chain { |
| 446 | if j > 0 && v.Kind() == reflect.Ptr { |
| 447 | if v.IsNil() { |
| 448 | if !v.CanSet() { |
| 449 | return reflect.Value{} |
| 450 | } |
| 451 | v.Set(reflect.New(v.Type().Elem())) |
| 452 | } |
| 453 | v = v.Elem() |
| 454 | } |
| 455 | v = v.Field(fi) |
| 456 | } |
| 457 | return v |
| 458 | } |
| 459 | |
| 460 | // decode fills a struct field using a parsed path. |
| 461 | func (d *Decoder) decode(v reflect.Value, path string, parts []pathPart, values []string, files []*multipart.FileHeader) error { |
| 462 | // Get the field walking the struct fields by index. |
| 463 | for _, hop := range parts[0].hops { |
| 464 | // A previous hop may have been blocked by an unsettable nil |
| 465 | // embedded pointer; the field is unreachable then. |
| 466 | if !v.IsValid() { |
| 467 | return nil |
| 468 | } |
| 469 | if v.Kind() == reflect.Ptr { |
| 470 | if v.IsNil() { |
| 471 | v.Set(reflect.New(v.Type().Elem())) |
| 472 | } |
| 473 | v = v.Elem() |
| 474 | } |
| 475 | |
| 476 | // Allocate embedded anonymous pointers required for promoted fields. |
| 477 | for _, idx := range hop.ensure { |
| 478 | if f := v.Field(idx); f.IsNil() { |
| 479 | f.Set(reflect.New(f.Type().Elem())) |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | v = walkIndexChain(v, hop.index) |
| 484 | } |
| 485 | |
| 486 | // Don't even bother for unexported fields. |
| 487 | if !v.CanSet() { |
| 488 | return nil |
| 489 | } |
| 490 | |
| 491 | // Fast path: plain builtin scalar fields skip the converter/unmarshaler |
| 492 | // dispatch below; fastKind was validated at cache-build time. |
| 493 | if k := parts[0].field.fastKind; k != reflect.Invalid && len(parts) == 1 && !parts[0].elem { |
| 494 | val := "" |
| 495 | if len(values) > 0 { |
| 496 | val = values[len(values)-1] |
| 497 | } |
| 498 | if val == "" { |
| 499 | if d.zeroEmpty { |
| 500 | v.SetZero() |
| 501 | } |
| 502 | return nil |
| 503 | } |
| 504 | if _, ok := setBuiltinKind(v, k, val); !ok { |
| 505 | return ConversionError{ |
| 506 | Key: path, |
| 507 | Type: parts[0].field.typ, |
| 508 | Index: -1, |
| 509 | } |
| 510 | } |
| 511 | return nil |
| 512 | } |
| 513 | |
| 514 | // Check multipart files |
| 515 | if parts[0].field.isMultipart && handleMultipartField(v, files) { |
| 516 | return nil |
| 517 | } |
| 518 | |
| 519 | // Dereference if needed. |
| 520 | t := v.Type() |
| 521 | if t.Kind() == reflect.Ptr { |
| 522 | t = t.Elem() |
| 523 | if v.IsNil() { |
| 524 | v.Set(reflect.New(t)) |
| 525 | } |
| 526 | v = v.Elem() |
| 527 | } |
| 528 | |
| 529 | // Slice of structs. Let's go recursive. |
| 530 | if len(parts) > 1 { |
| 531 | idx := parts[0].index |
| 532 | // a defensive check to avoid creating a large slice based on user input index |
| 533 | if idx > d.maxSize { |
| 534 | return fmt.Errorf("%v index %d is larger than the configured maxSize %d", v.Kind(), idx, d.maxSize) |
| 535 | } |
| 536 | if v.IsNil() || v.Len() < idx+1 { |
| 537 | // Grow into a fresh backing array: extending within existing |
| 538 | // capacity would write into memory the caller may still share |
| 539 | // through other slices aliasing the original array. |
| 540 | value := reflect.MakeSlice(t, idx+1, idx+1) |
| 541 | if v.Len() > 0 { |
| 542 | // Resize it. |
| 543 | reflect.Copy(value, v) |
| 544 | } |
| 545 | v.Set(value) |
| 546 | } |
| 547 | return d.decode(v.Index(idx), path, parts[1:], values, files) |
| 548 | } |
| 549 | |
| 550 | // Get the converter early in case there is one for a slice type. |
| 551 | conv := d.cache.converter(t) |
| 552 | // The encoding.TextUnmarshaler facts for v's type are precomputed per |
| 553 | // field; instances are bound to live values where needed below. For an |
| 554 | // elem part (path terminated at a slice index) v is an element of the |
| 555 | // slice field, so the element type's facts apply. |
| 556 | m := parts[0].field.derefUnmarshaler |
| 557 | if parts[0].elem { |
| 558 | m = parts[0].field.elemUnmarshaler |
| 559 | } |
| 560 | if conv == nil && t.Kind() == reflect.Slice && m.IsSliceElement { |
| 561 | elemT := t.Elem() |
| 562 | isPtrElem := elemT.Kind() == reflect.Ptr |
| 563 | if isPtrElem { |
| 564 | elemT = elemT.Elem() |
| 565 | } |
| 566 | |
| 567 | // Try to get a converter for the element type. |
| 568 | customConv := d.cache.converter(elemT) |
| 569 | conv := customConv |
| 570 | if conv == nil { |
| 571 | conv = getBuiltinConverter(elemT.Kind()) |
| 572 | if conv == nil { |
| 573 | // As we are not dealing with slice of structs here, we don't need to check if the type |
| 574 | // implements TextUnmarshaler interface |
| 575 | return fmt.Errorf("schema: converter not found for %v", elemT) |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | // Fast path: builtin element kinds without unmarshalers, custom |
| 580 | // converters or pointer elements decode straight into a fresh slice, |
| 581 | // avoiding one reflect.Value allocation per element. |
| 582 | if customConv == nil && !m.IsValid && !isPtrElem { |
| 583 | return d.decodeBuiltinSlice(v, t, path, values) |
| 584 | } |
| 585 | |
| 586 | itemsBuf := decodeValueBufferPool.Get().(*[]reflect.Value) |
| 587 | items := (*itemsBuf)[:0] |
| 588 | defer func() { |
| 589 | clear(items) |
| 590 | *itemsBuf = items[:0] |
| 591 | decodeValueBufferPool.Put(itemsBuf) |
| 592 | }() |
| 593 | |
| 594 | for key, value := range values { |
| 595 | if value == "" { |
| 596 | if d.zeroEmpty { |
| 597 | items = append(items, reflect.Zero(t.Elem())) |
| 598 | } |
| 599 | } else if m.IsValid { |
| 600 | u := reflect.New(elemT) |
| 601 | if m.IsSliceElementPtr { |
| 602 | u = reflect.New(reflect.PointerTo(elemT).Elem()) |
| 603 | } |
| 604 | um, _ := reflect.TypeAssert[encoding.TextUnmarshaler](u) |
| 605 | if err := um.UnmarshalText([]byte(value)); err != nil { |
| 606 | return ConversionError{ |
| 607 | Key: path, |
| 608 | Type: t, |
| 609 | Index: key, |
| 610 | Err: err, |
| 611 | } |
| 612 | } |
| 613 | if m.IsSliceElementPtr { |
| 614 | items = append(items, u.Elem().Addr()) |
| 615 | } else { |
| 616 | // u is always a pointer from reflect.New; store the |
| 617 | // pointed-to value. |
| 618 | items = append(items, u.Elem()) |
| 619 | } |
| 620 | } else if item := conv(value); item.IsValid() { |
| 621 | items = appendConvertedItem(items, item, elemT, isPtrElem) |
| 622 | } else { |
| 623 | if strings.IndexByte(value, ',') != -1 { |
| 624 | for value := range strings.SplitSeq(value, ",") { |
| 625 | if value == "" { |
| 626 | if d.zeroEmpty { |
| 627 | items = append(items, reflect.Zero(t.Elem())) |
| 628 | } |
| 629 | } else if item := conv(value); item.IsValid() { |
| 630 | items = appendConvertedItem(items, item, elemT, isPtrElem) |
| 631 | } else { |
| 632 | return ConversionError{ |
| 633 | Key: path, |
| 634 | Type: elemT, |
| 635 | Index: key, |
| 636 | } |
| 637 | } |
| 638 | } |
| 639 | } else { |
| 640 | return ConversionError{ |
| 641 | Key: path, |
| 642 | Type: elemT, |
| 643 | Index: key, |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | } |
| 648 | value := reflect.MakeSlice(t, len(items), len(items)) |
| 649 | for i, item := range items { |
| 650 | value.Index(i).Set(item) |
| 651 | } |
| 652 | v.Set(value) |
| 653 | } else { |
| 654 | val := "" |
| 655 | // Use the last value provided if any values were provided |
| 656 | if len(values) > 0 { |
| 657 | val = values[len(values)-1] |
| 658 | } |
| 659 | |
| 660 | if conv != nil { |
| 661 | if value := conv(val); value.IsValid() { |
| 662 | v.Set(value.Convert(t)) |
| 663 | } else { |
| 664 | return ConversionError{ |
| 665 | Key: path, |
| 666 | Type: t, |
| 667 | Index: -1, |
| 668 | } |
| 669 | } |
| 670 | } else if m.IsValid { |
| 671 | if m.IsPtr { |
| 672 | u := reflect.New(v.Type()) |
| 673 | um, _ := reflect.TypeAssert[encoding.TextUnmarshaler](u) |
| 674 | if err := um.UnmarshalText([]byte(val)); err != nil { |
| 675 | return ConversionError{ |
| 676 | Key: path, |
| 677 | Type: t, |
| 678 | Index: -1, |
| 679 | Err: err, |
| 680 | } |
| 681 | } |
| 682 | v.Set(reflect.Indirect(u)) |
| 683 | } else { |
| 684 | // If the value implements the encoding.TextUnmarshaler interface |
| 685 | // apply UnmarshalText as the converter, binding it to the |
| 686 | // live value. |
| 687 | um, _ := reflect.TypeAssert[encoding.TextUnmarshaler](v) |
| 688 | if err := um.UnmarshalText([]byte(val)); err != nil { |
| 689 | return ConversionError{ |
| 690 | Key: path, |
| 691 | Type: t, |
| 692 | Index: -1, |
| 693 | Err: err, |
| 694 | } |
| 695 | } |
| 696 | } |
| 697 | } else if val == "" { |
| 698 | if d.zeroEmpty { |
| 699 | v.Set(reflect.Zero(t)) |
| 700 | } |
| 701 | } else if handled, ok := setBuiltinKind(v, t.Kind(), val); handled { |
| 702 | if !ok { |
| 703 | return ConversionError{ |
| 704 | Key: path, |
| 705 | Type: t, |
| 706 | Index: -1, |
| 707 | } |
| 708 | } |
| 709 | } else { |
| 710 | return fmt.Errorf("schema: converter not found for %v", t) |
| 711 | } |
| 712 | } |
| 713 | return nil |
| 714 | } |
| 715 | |
| 716 | // appendConvertedItem converts a builtin/custom converter result to the slice |
| 717 | // element type and appends it, wrapping it in a freshly allocated pointer for |
| 718 | // pointer-element slices. The conversion must happen before the pointer wrap: |
| 719 | // builtin converters return the underlying kind (e.g. int for a named |
| 720 | // `type MyInt int`), which is not assignable to the named element type, so |
| 721 | // Set-ing it into a *MyInt without converting first panics. |
| 722 | func appendConvertedItem(items []reflect.Value, item reflect.Value, elemT reflect.Type, isPtrElem bool) []reflect.Value { |
| 723 | if item.Type() != elemT { |
| 724 | item = item.Convert(elemT) |
| 725 | } |
| 726 | if isPtrElem { |
| 727 | ptr := reflect.New(elemT) |
| 728 | ptr.Elem().Set(item) |
| 729 | item = ptr |
| 730 | } |
| 731 | return append(items, item) |
| 732 | } |
| 733 | |
| 734 | // decodeBuiltinSlice decodes values into the slice field v of type t whose |
| 735 | // elements are builtin-convertible kinds, parsing directly into slice slots |
| 736 | // instead of boxing every element in a reflect.Value. The slice is built |
| 737 | // detached and only assigned to v when every value parsed, matching the |
| 738 | // all-or-nothing behavior of the generic path. |
| 739 | // |
| 740 | // A value that fails to parse as a whole is retried as a comma-separated |
| 741 | // list. For non-string kinds a value containing a comma can never parse as a |
| 742 | // whole (no builtin syntax admits commas — pinned by a test), and string |
| 743 | // values always parse, so item boundaries are knowable upfront: the slice is |
| 744 | // sized by a cheap comma count (an upper bound, since empty items may be |
| 745 | // skipped) and truncated to the filled length at the end. |
| 746 | func (d *Decoder) decodeBuiltinSlice(v reflect.Value, t reflect.Type, path string, values []string) error { |
| 747 | elemT := t.Elem() |
| 748 | k := elemT.Kind() |
| 749 | split := k != reflect.String |
| 750 | |
| 751 | n := 0 |
| 752 | for _, value := range values { |
| 753 | if split { |
| 754 | n += strings.Count(value, ",") |
| 755 | } |
| 756 | n++ |
| 757 | } |
| 758 | |
| 759 | // Exact builtin slice types decode without per-element reflect calls; |
| 760 | // named slice or element types fall through to the generic path. |
| 761 | switch t { |
| 762 | case typSliceString: |
| 763 | return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeString) |
| 764 | case typSliceInt: |
| 765 | return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeInt) |
| 766 | case typSliceInt64: |
| 767 | return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeInt64) |
| 768 | case typSliceUint: |
| 769 | return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeUint) |
| 770 | case typSliceUint64: |
| 771 | return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeUint64) |
| 772 | case typSliceFloat64: |
| 773 | return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeFloat64) |
| 774 | case typSliceBool: |
| 775 | return decodeNativeSlice(d.zeroEmpty, v, path, values, elemT, n, split, parseNativeBool) |
| 776 | } |
| 777 | |
| 778 | sl := reflect.MakeSlice(t, n, n) |
| 779 | i := 0 |
| 780 | for key, value := range values { |
| 781 | switch { |
| 782 | case value == "": |
| 783 | if d.zeroEmpty { |
| 784 | i++ // slot stays zero |
| 785 | } |
| 786 | case split && strings.IndexByte(value, ',') != -1: |
| 787 | for item := range strings.SplitSeq(value, ",") { |
| 788 | if item == "" { |
| 789 | if d.zeroEmpty { |
| 790 | i++ // slot stays zero |
| 791 | } |
| 792 | continue |
| 793 | } |
| 794 | if _, ok := setBuiltinKind(sl.Index(i), k, item); !ok { |
| 795 | return ConversionError{ |
| 796 | Key: path, |
| 797 | Type: elemT, |
| 798 | Index: key, |
| 799 | } |
| 800 | } |
| 801 | i++ |
| 802 | } |
| 803 | default: |
| 804 | if _, ok := setBuiltinKind(sl.Index(i), k, value); !ok { |
| 805 | return ConversionError{ |
| 806 | Key: path, |
| 807 | Type: elemT, |
| 808 | Index: key, |
| 809 | } |
| 810 | } |
| 811 | i++ |
| 812 | } |
| 813 | } |
| 814 | if i < n { |
| 815 | sl = sl.Slice(0, i) |
| 816 | } |
| 817 | v.Set(sl) |
| 818 | return nil |
| 819 | } |
| 820 | |
| 821 | // Exact (unnamed) builtin slice types eligible for the native decode path. |
| 822 | var ( |
| 823 | typSliceString = reflect.TypeOf([]string(nil)) |
| 824 | typSliceInt = reflect.TypeOf([]int(nil)) |
| 825 | typSliceInt64 = reflect.TypeOf([]int64(nil)) |
| 826 | typSliceUint = reflect.TypeOf([]uint(nil)) |
| 827 | typSliceUint64 = reflect.TypeOf([]uint64(nil)) |
| 828 | typSliceFloat64 = reflect.TypeOf([]float64(nil)) |
| 829 | typSliceBool = reflect.TypeOf([]bool(nil)) |
| 830 | ) |
| 831 | |
| 832 | // decodeNativeSlice mirrors the generic decodeBuiltinSlice loop for a field |
| 833 | // typed exactly []T, parsing into a native slice assigned only if every value |
| 834 | // parsed (all-or-nothing). n is the precomputed element upper bound. |
| 835 | func decodeNativeSlice[T any](zeroEmpty bool, v reflect.Value, path string, values []string, elemT reflect.Type, n int, split bool, parse func(string) (T, bool)) error { |
| 836 | out := make([]T, 0, n) |
| 837 | var zero T |
| 838 | for key, value := range values { |
| 839 | switch { |
| 840 | case value == "": |
| 841 | if zeroEmpty { |
| 842 | out = append(out, zero) |
| 843 | } |
| 844 | case split && strings.IndexByte(value, ',') != -1: |
| 845 | for item := range strings.SplitSeq(value, ",") { |
| 846 | if item == "" { |
| 847 | if zeroEmpty { |
| 848 | out = append(out, zero) |
| 849 | } |
| 850 | continue |
| 851 | } |
| 852 | ev, ok := parse(item) |
| 853 | if !ok { |
| 854 | return ConversionError{ |
| 855 | Key: path, |
| 856 | Type: elemT, |
| 857 | Index: key, |
| 858 | } |
| 859 | } |
| 860 | out = append(out, ev) |
| 861 | } |
| 862 | default: |
| 863 | ev, ok := parse(value) |
| 864 | if !ok { |
| 865 | return ConversionError{ |
| 866 | Key: path, |
| 867 | Type: elemT, |
| 868 | Index: key, |
| 869 | } |
| 870 | } |
| 871 | out = append(out, ev) |
| 872 | } |
| 873 | } |
| 874 | // v's type is exactly []T here (the dispatch switch guarantees it), so |
| 875 | // assign through the typed pointer: no reflect.ValueOf escape, no Set |
| 876 | // assignability checks, and a loud panic if the invariant is ever broken. |
| 877 | *v.Addr().Interface().(*[]T) = out |
| 878 | return nil |
| 879 | } |
| 880 | |
| 881 | func isTextUnmarshaler(v reflect.Value) unmarshaler { |
| 882 | // Create a new unmarshaller instance |
| 883 | m := unmarshaler{} |
| 884 | if _, m.IsValid = reflect.TypeAssert[encoding.TextUnmarshaler](v); m.IsValid { |
| 885 | return m |
| 886 | } |
| 887 | // As the UnmarshalText function should be applied to the pointer of the |
| 888 | // type, we check that type to see if it implements the necessary |
| 889 | // method. |
| 890 | if _, m.IsValid = reflect.TypeAssert[encoding.TextUnmarshaler](reflect.New(v.Type())); m.IsValid { |
| 891 | m.IsPtr = true |
| 892 | return m |
| 893 | } |
| 894 | |
| 895 | // if v is []T or *[]T create new T |
| 896 | t := v.Type() |
| 897 | if t.Kind() == reflect.Ptr { |
| 898 | t = t.Elem() |
| 899 | } |
| 900 | if t.Kind() == reflect.Slice { |
| 901 | // The slice type itself cannot implement encoding.TextUnmarshaler |
| 902 | // here: the value-level assert above already covered it. Check |
| 903 | // whether the elements do. |
| 904 | m.IsSliceElement = true |
| 905 | if t = t.Elem(); t.Kind() == reflect.Ptr { |
| 906 | t = reflect.PointerTo(t.Elem()) |
| 907 | m.IsSliceElementPtr = true |
| 908 | _, m.IsValid = reflect.TypeAssert[encoding.TextUnmarshaler](reflect.Zero(t)) |
| 909 | return m |
| 910 | } |
| 911 | } |
| 912 | |
| 913 | _, m.IsValid = reflect.TypeAssert[encoding.TextUnmarshaler](reflect.New(t)) |
| 914 | return m |
| 915 | } |
| 916 | |
| 917 | // TextUnmarshaler helpers ---------------------------------------------------- |
| 918 | // unmarshaler describes how a type relates to encoding.TextUnmarshaler. |
| 919 | // It carries type-level facts only; the decoder binds instances to live |
| 920 | // values at the point of use. |
| 921 | type unmarshaler struct { |
| 922 | // IsValid indicates whether the resolved type indicated by the other |
| 923 | // flags implements the encoding.TextUnmarshaler interface. |
| 924 | IsValid bool |
| 925 | // IsPtr indicates that the resolved type is the pointer of the original |
| 926 | // type. |
| 927 | IsPtr bool |
| 928 | // IsSliceElement indicates that the resolved type is a slice element of |
| 929 | // the original type. |
| 930 | IsSliceElement bool |
| 931 | // IsSliceElementPtr indicates that the resolved type is a pointer to a |
| 932 | // slice element of the original type. |
| 933 | IsSliceElementPtr bool |
| 934 | } |
| 935 | |
| 936 | // Errors --------------------------------------------------------------------- |
| 937 | |
| 938 | // ConversionError stores information about a failed conversion. |
| 939 | type ConversionError struct { |
| 940 | Key string // key from the source map. |
| 941 | Type reflect.Type // expected type of elem |
| 942 | Index int // index for multi-value fields; -1 for single-value fields. |
| 943 | Err error // low-level error (when it exists) |
| 944 | } |
| 945 | |
| 946 | func (e ConversionError) Error() string { |
| 947 | var output string |
| 948 | |
| 949 | if e.Index < 0 { |
| 950 | output = fmt.Sprintf("schema: error converting value for %q", e.Key) |
| 951 | } else { |
| 952 | output = fmt.Sprintf("schema: error converting value for index %d of %q", |
| 953 | e.Index, e.Key) |
| 954 | } |
| 955 | |
| 956 | if e.Err != nil { |
| 957 | output = fmt.Sprintf("%s. Details: %s", output, e.Err) |
| 958 | } |
| 959 | |
| 960 | return output |
| 961 | } |
| 962 | |
| 963 | // UnknownKeyError stores information about an unknown key in the source map. |
| 964 | type UnknownKeyError struct { |
| 965 | Key string // key from the source map. |
| 966 | } |
| 967 | |
| 968 | func (e UnknownKeyError) Error() string { |
| 969 | return fmt.Sprintf("schema: invalid path %q", e.Key) |
| 970 | } |
| 971 | |
| 972 | // EmptyFieldError stores information about an empty required field. |
| 973 | type EmptyFieldError struct { |
| 974 | Key string // required key in the source map. |
| 975 | } |
| 976 | |
| 977 | func (e EmptyFieldError) Error() string { |
| 978 | return fmt.Sprintf("%v is empty", e.Key) |
| 979 | } |
| 980 | |
| 981 | // MultiError stores multiple decoding errors. |
| 982 | // |
| 983 | // Borrowed from the App Engine SDK. |
| 984 | type MultiError map[string]error |
| 985 | |
| 986 | func (e MultiError) Error() string { |
| 987 | s := "" |
| 988 | for _, err := range e { |
| 989 | s = err.Error() |
| 990 | break |
| 991 | } |
| 992 | switch len(e) { |
| 993 | case 0: |
| 994 | return "(0 errors)" |
| 995 | case 1: |
| 996 | return s |
| 997 | case 2: |
| 998 | return s + " (and 1 other error)" |
| 999 | } |
| 1000 | return fmt.Sprintf("%s (and %d other errors)", s, len(e)-1) |
| 1001 | } |
| 1002 | |
| 1003 | func appendRequiredField(m map[string][]fieldWithPrefix, key string, field fieldWithPrefix) map[string][]fieldWithPrefix { |
| 1004 | if m == nil { |
| 1005 | m = make(map[string][]fieldWithPrefix) |
| 1006 | } |
| 1007 | m[key] = append(m[key], field) |
| 1008 | return m |
| 1009 | } |
| 1010 | |
| 1011 | func appendError(m MultiError, key string, err error) MultiError { |
| 1012 | if err == nil { |
| 1013 | return m |
| 1014 | } |
| 1015 | if m == nil { |
| 1016 | m = make(MultiError) |
| 1017 | } |
| 1018 | if m[key] == nil { |
| 1019 | m[key] = err |
| 1020 | } |
| 1021 | return m |
| 1022 | } |
| 1023 | |
| 1024 | func mergeErrors(dst, src MultiError) MultiError { |
| 1025 | if len(src) == 0 { |
| 1026 | return dst |
| 1027 | } |
| 1028 | if dst == nil { |
| 1029 | dst = make(MultiError, len(src)) |
| 1030 | } |
| 1031 | for key, err := range src { |
| 1032 | if dst[key] == nil { |
| 1033 | dst[key] = err |
| 1034 | } |
| 1035 | } |
| 1036 | return dst |
| 1037 | } |