| 1 | package schema |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "reflect" |
| 7 | "strconv" |
| 8 | "sync" |
| 9 | "sync/atomic" |
| 10 | |
| 11 | utils "github.com/gofiber/utils/v2" |
| 12 | ) |
| 13 | |
| 14 | type encoderFunc func(reflect.Value) string |
| 15 | |
| 16 | // errNotStruct is returned by Encode for invalid sources; hoisted so the |
| 17 | // check does not allocate on every call. |
| 18 | var errNotStruct = errors.New("schema: interface must be a struct") |
| 19 | |
| 20 | // errNilDst is returned by Encode when the destination map is nil, which |
| 21 | // would otherwise panic on the first map assignment. |
| 22 | var errNilDst = errors.New("schema: dst map must not be nil") |
| 23 | |
| 24 | // maxScratchValueLen bounds values stored in encode's shared scratch array, |
| 25 | // capping how much data a surviving dst entry can keep reachable after the |
| 26 | // caller deletes neighboring keys. Only strings allocated by this package's |
| 27 | // own formatters are eligible at all (see encField.scratchSafe), so the cap |
| 28 | // bounds real bytes, not just headers. |
| 29 | const maxScratchValueLen = 64 |
| 30 | |
| 31 | // Encoder encodes values from a struct into url.Values. |
| 32 | type Encoder struct { |
| 33 | cache *cache |
| 34 | regenc map[reflect.Type]encoderFunc |
| 35 | // encCache memoizes the per-struct-type encoding plan |
| 36 | // (map[reflect.Type][]encField) so tags are parsed and encoder |
| 37 | // functions resolved once per type instead of on every Encode call. |
| 38 | encCache sync.Map |
| 39 | // encGen is bumped before encCache is cleared on configuration changes; |
| 40 | // structInfo snapshots it before building a plan and refuses to store |
| 41 | // the plan if it changed, so a build racing a reconfiguration cannot |
| 42 | // re-insert a stale plan after the clear. |
| 43 | encGen atomic.Uint64 |
| 44 | } |
| 45 | |
| 46 | // encPlan tags a per-type encoding plan with the configuration generation it |
| 47 | // was built under: hit-validation ignores plans from older generations, so |
| 48 | // any Encode starting after a reconfiguration returns observes the new |
| 49 | // configuration even if a racing build stored a stale plan after the clear. |
| 50 | type encPlan struct { |
| 51 | fields []encField |
| 52 | gen uint64 |
| 53 | } |
| 54 | |
| 55 | // encField is the precomputed encoding plan for one struct field. |
| 56 | type encField struct { |
| 57 | name string |
| 58 | enc encoderFunc // immediate encoder; nil for structs and slices |
| 59 | elemEnc encoderFunc // slice element encoder, when the field is a slice |
| 60 | idx int |
| 61 | omitEmpty bool |
| 62 | // recurseStructPtr marks pointer-to-struct fields without a custom |
| 63 | // encoder: non-nil values are encoded by recursing into the element. |
| 64 | recurseStructPtr bool |
| 65 | // scratchSafe marks fields whose encoder output is allocated by this |
| 66 | // package (numeric/bool/float formatters), so it can never alias a large |
| 67 | // caller-owned buffer and may be batched in encode's shared scratch. |
| 68 | scratchSafe bool |
| 69 | isStruct bool |
| 70 | // nilAsNull marks pointer fields whose element has no immediate |
| 71 | // encoder (structs recursed via recurseStructPtr, or unsupported |
| 72 | // types): nil values encode as "null", matching the closure behavior |
| 73 | // pointer fields with encodable elements get. |
| 74 | nilAsNull bool |
| 75 | // elemPtrNil marks slice fields whose element is a pointer type with no |
| 76 | // encoder (e.g. []*Struct): nil elements encode as "null" (as they did |
| 77 | // historically), while a non-nil such element is an error. |
| 78 | elemPtrNil bool |
| 79 | } |
| 80 | |
| 81 | // NewEncoder returns a new Encoder with defaults. |
| 82 | func NewEncoder() *Encoder { |
| 83 | return &Encoder{cache: newCache(), regenc: make(map[reflect.Type]encoderFunc)} |
| 84 | } |
| 85 | |
| 86 | // Encode encodes a struct into map[string][]string. |
| 87 | // |
| 88 | // Intended for use with url.Values. |
| 89 | func (e *Encoder) Encode(src interface{}, dst map[string][]string) (err error) { |
| 90 | if dst == nil { |
| 91 | return errNilDst |
| 92 | } |
| 93 | |
| 94 | // Catch panics from reflection or user-registered encoders and return |
| 95 | // them as an error instead of crashing the caller, mirroring Decode. |
| 96 | defer func() { |
| 97 | if r := recover(); r != nil { |
| 98 | if e, ok := r.(error); ok { |
| 99 | err = e |
| 100 | } else { |
| 101 | err = fmt.Errorf("schema: panic while encoding: %v", r) |
| 102 | } |
| 103 | } |
| 104 | }() |
| 105 | |
| 106 | v := reflect.ValueOf(src) |
| 107 | |
| 108 | return e.encode(v, dst) |
| 109 | } |
| 110 | |
| 111 | // RegisterEncoder registers a converter for encoding a custom type. |
| 112 | func (e *Encoder) RegisterEncoder(value interface{}, encoder func(reflect.Value) string) { |
| 113 | e.cache.l.Lock() |
| 114 | e.regenc[reflect.TypeOf(value)] = encoder |
| 115 | e.cache.l.Unlock() |
| 116 | e.encGen.Add(1) |
| 117 | e.encCache.Clear() |
| 118 | } |
| 119 | |
| 120 | // SetAliasTag changes the tag used to locate custom field aliases. |
| 121 | // The default tag is "schema". |
| 122 | func (e *Encoder) SetAliasTag(tag string) { |
| 123 | e.cache.l.Lock() |
| 124 | e.cache.tag = tag |
| 125 | e.cache.l.Unlock() |
| 126 | e.encGen.Add(1) |
| 127 | e.encCache.Clear() |
| 128 | } |
| 129 | |
| 130 | // structInfo returns the cached encoding plan for struct type t, building it |
| 131 | // on first use. The build reads the tag and registered encoders under the |
| 132 | // configuration lock; the generation re-checks around the cache store keep a |
| 133 | // build racing a reconfiguration from inserting a stale plan. |
| 134 | func (e *Encoder) structInfo(t reflect.Type) []encField { |
| 135 | gen := e.encGen.Load() |
| 136 | if cached, ok := e.encCache.Load(t); ok { |
| 137 | // Ignore plans built under an older configuration; fall through and |
| 138 | // rebuild (the fresh plan overwrites the stale entry). |
| 139 | if p := cached.(*encPlan); p.gen == gen { |
| 140 | return p.fields |
| 141 | } |
| 142 | } |
| 143 | e.cache.l.RLock() |
| 144 | tag := e.cache.tag |
| 145 | fields := make([]encField, 0, t.NumField()) |
| 146 | for i := 0; i < t.NumField(); i++ { |
| 147 | sf := t.Field(i) |
| 148 | name, opts := fieldAlias(sf, tag) |
| 149 | if name == "-" { |
| 150 | continue |
| 151 | } |
| 152 | ft := sf.Type |
| 153 | f := encField{ |
| 154 | idx: i, |
| 155 | name: name, |
| 156 | omitEmpty: opts.Contains("omitempty"), |
| 157 | recurseStructPtr: ft.Kind() == reflect.Ptr && |
| 158 | ft.Elem().Kind() == reflect.Struct && |
| 159 | !e.hasCustomEncoder(ft), |
| 160 | enc: typeEncoder(ft, e.regenc), |
| 161 | scratchSafe: scratchSafeEncoder(ft, e.regenc), |
| 162 | } |
| 163 | if f.enc == nil { |
| 164 | switch ft.Kind() { |
| 165 | case reflect.Struct: |
| 166 | f.isStruct = true |
| 167 | case reflect.Slice: |
| 168 | f.elemEnc = typeEncoder(ft.Elem(), e.regenc) |
| 169 | if f.elemEnc == nil && ft.Elem().Kind() == reflect.Ptr { |
| 170 | f.elemPtrNil = true |
| 171 | } |
| 172 | case reflect.Ptr: |
| 173 | f.nilAsNull = true |
| 174 | } |
| 175 | } |
| 176 | fields = append(fields, f) |
| 177 | } |
| 178 | e.cache.l.RUnlock() |
| 179 | // Don't cache a plan whose inputs (tag, registered encoders) changed |
| 180 | // while it was being built; the next call rebuilds it fresh. Even if a |
| 181 | // stale plan slips in after the clear, its generation tag keeps it from |
| 182 | // ever being served. |
| 183 | if e.encGen.Load() == gen { |
| 184 | e.encCache.Store(t, &encPlan{fields: fields, gen: gen}) |
| 185 | } |
| 186 | return fields |
| 187 | } |
| 188 | |
| 189 | func isZero(v reflect.Value) bool { |
| 190 | switch v.Kind() { |
| 191 | case reflect.Func: |
| 192 | case reflect.Map, reflect.Slice: |
| 193 | return v.IsNil() || v.Len() == 0 |
| 194 | case reflect.Array: |
| 195 | for i := 0; i < v.Len(); i++ { |
| 196 | if !isZero(v.Index(i)) { |
| 197 | return false |
| 198 | } |
| 199 | } |
| 200 | return true |
| 201 | case reflect.Struct: |
| 202 | if v.CanInterface() { |
| 203 | if iz, ok := v.Interface().(interface{ IsZero() bool }); ok { |
| 204 | return iz.IsZero() |
| 205 | } |
| 206 | } |
| 207 | for i := 0; i < v.NumField(); i++ { |
| 208 | if !isZero(v.Field(i)) { |
| 209 | return false |
| 210 | } |
| 211 | } |
| 212 | return true |
| 213 | } |
| 214 | // Compare other types directly: |
| 215 | return v.IsZero() |
| 216 | } |
| 217 | |
| 218 | func (e *Encoder) encode(v reflect.Value, dst map[string][]string) error { |
| 219 | if v.Kind() == reflect.Ptr { |
| 220 | v = v.Elem() |
| 221 | } |
| 222 | if v.Kind() != reflect.Struct { |
| 223 | return errNotStruct |
| 224 | } |
| 225 | |
| 226 | var errs MultiError |
| 227 | |
| 228 | fields := e.structInfo(v.Type()) |
| 229 | // When dst starts empty (fresh url.Values), single short package-allocated |
| 230 | // values of distinct keys share one backing array instead of allocating a |
| 231 | // 1-element slice each; the three-index slice caps entries so later |
| 232 | // appends cannot overwrite a neighbor. Caller-derived strings (string |
| 233 | // fields, custom encoders) and long values get their own independently |
| 234 | // collectible slice so a surviving entry cannot keep a deleted neighbor's |
| 235 | // allocation alive; a non-empty dst keeps the single-map-op append pattern. |
| 236 | useScratch := len(dst) == 0 |
| 237 | var scratch []string |
| 238 | appendValue := func(name, s string, scratchSafe bool) { |
| 239 | if !useScratch || !scratchSafe || len(s) > maxScratchValueLen { |
| 240 | dst[name] = append(dst[name], s) |
| 241 | return |
| 242 | } |
| 243 | if old := dst[name]; old != nil { |
| 244 | dst[name] = append(old, s) |
| 245 | return |
| 246 | } |
| 247 | if scratch == nil { |
| 248 | scratch = make([]string, 0, len(fields)) |
| 249 | } |
| 250 | scratch = append(scratch, s) |
| 251 | dst[name] = scratch[len(scratch)-1 : len(scratch) : len(scratch)] |
| 252 | } |
| 253 | for i := range fields { |
| 254 | f := &fields[i] |
| 255 | fieldValue := v.Field(f.idx) |
| 256 | |
| 257 | // Encode struct pointer types if the field is a valid pointer and a struct. |
| 258 | if f.recurseStructPtr && !fieldValue.IsNil() { |
| 259 | if err := e.encode(fieldValue.Elem(), dst); err != nil { |
| 260 | errs = setError(errs, fieldValue.Elem().Type().String(), err) |
| 261 | } |
| 262 | continue |
| 263 | } |
| 264 | |
| 265 | // Encode non-slice types and custom implementations immediately. |
| 266 | if f.enc != nil { |
| 267 | if f.omitEmpty && isZero(fieldValue) { |
| 268 | continue |
| 269 | } |
| 270 | appendValue(f.name, f.enc(fieldValue), f.scratchSafe) |
| 271 | continue |
| 272 | } |
| 273 | |
| 274 | if f.nilAsNull && fieldValue.IsNil() { |
| 275 | if f.omitEmpty { |
| 276 | continue |
| 277 | } |
| 278 | // The "null" literal is static data; always scratch-safe. |
| 279 | appendValue(f.name, "null", true) |
| 280 | continue |
| 281 | } |
| 282 | |
| 283 | if f.isStruct { |
| 284 | if err := e.encode(fieldValue, dst); err != nil { |
| 285 | errs = setError(errs, fieldValue.Type().String(), err) |
| 286 | } |
| 287 | continue |
| 288 | } |
| 289 | |
| 290 | // A non-slice field with no encoder (map, chan, array, or a non-nil |
| 291 | // pointer to an unencodable type), or a slice whose element type is |
| 292 | // itself unencodable and not a pointer (e.g. []Struct), cannot be |
| 293 | // encoded — historically this errored unconditionally. |
| 294 | if fieldValue.Kind() != reflect.Slice || (f.elemEnc == nil && !f.elemPtrNil) { |
| 295 | errs = setError(errs, fieldValue.Type().String(), fmt.Errorf("schema: encoder not found for %v", fieldValue)) |
| 296 | continue |
| 297 | } |
| 298 | |
| 299 | // Encode a slice. An empty slice has nothing to encode, so it is |
| 300 | // skipped under omitempty (and otherwise emitted empty). |
| 301 | n := fieldValue.Len() |
| 302 | if n == 0 && f.omitEmpty { |
| 303 | continue |
| 304 | } |
| 305 | |
| 306 | values := make([]string, n) |
| 307 | if f.elemEnc == nil { |
| 308 | // Pointer elements with no encoder (elemPtrNil): nil encodes as |
| 309 | // "null" (as historically), a non-nil such element is an error. |
| 310 | bad := false |
| 311 | for j := 0; j < n; j++ { |
| 312 | if fieldValue.Index(j).IsNil() { |
| 313 | values[j] = "null" |
| 314 | continue |
| 315 | } |
| 316 | errs = setError(errs, fieldValue.Type().String(), fmt.Errorf("schema: encoder not found for %v", fieldValue)) |
| 317 | bad = true |
| 318 | break |
| 319 | } |
| 320 | if bad { |
| 321 | continue |
| 322 | } |
| 323 | } else { |
| 324 | for j := 0; j < n; j++ { |
| 325 | values[j] = f.elemEnc(fieldValue.Index(j)) |
| 326 | } |
| 327 | } |
| 328 | dst[f.name] = values |
| 329 | } |
| 330 | |
| 331 | if len(errs) > 0 { |
| 332 | return errs |
| 333 | } |
| 334 | return nil |
| 335 | } |
| 336 | |
| 337 | // setError lazily allocates m and stores err under key, overwriting any |
| 338 | // previous entry (matching the historical encoder error semantics). |
| 339 | func setError(m MultiError, key string, err error) MultiError { |
| 340 | if m == nil { |
| 341 | m = make(MultiError) |
| 342 | } |
| 343 | m[key] = err |
| 344 | return m |
| 345 | } |
| 346 | |
| 347 | func (e *Encoder) hasCustomEncoder(t reflect.Type) bool { |
| 348 | _, exists := e.regenc[t] |
| 349 | return exists |
| 350 | } |
| 351 | |
| 352 | // scratchSafeEncoder reports whether typeEncoder(t, reg)'s output strings are |
| 353 | // always allocated by this package's own formatters: string fields return the |
| 354 | // caller's string and custom encoders may return anything — either could be a |
| 355 | // small substring aliasing a large buffer, so neither may enter the scratch. |
| 356 | func scratchSafeEncoder(t reflect.Type, reg map[reflect.Type]encoderFunc) bool { |
| 357 | if _, ok := reg[t]; ok { |
| 358 | return false |
| 359 | } |
| 360 | switch t.Kind() { |
| 361 | case reflect.Bool, |
| 362 | reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, |
| 363 | reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, |
| 364 | reflect.Float32, reflect.Float64: |
| 365 | return true |
| 366 | case reflect.Ptr: |
| 367 | return scratchSafeEncoder(t.Elem(), reg) |
| 368 | default: |
| 369 | return false |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | func typeEncoder(t reflect.Type, reg map[reflect.Type]encoderFunc) encoderFunc { |
| 374 | if f, ok := reg[t]; ok { |
| 375 | return f |
| 376 | } |
| 377 | |
| 378 | switch t.Kind() { |
| 379 | case reflect.Bool: |
| 380 | return encodeBool |
| 381 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 382 | return encodeInt |
| 383 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: |
| 384 | return encodeUint |
| 385 | case reflect.Float32: |
| 386 | return encodeFloat32 |
| 387 | case reflect.Float64: |
| 388 | return encodeFloat64 |
| 389 | case reflect.Ptr: |
| 390 | f := typeEncoder(t.Elem(), reg) |
| 391 | if f == nil { |
| 392 | // No encoder for the element: report unsupported instead of |
| 393 | // returning a closure that would panic on non-nil values. |
| 394 | // Nil handling for such fields is done by encField.nilAsNull. |
| 395 | return nil |
| 396 | } |
| 397 | return func(v reflect.Value) string { |
| 398 | if v.IsNil() { |
| 399 | return "null" |
| 400 | } |
| 401 | return f(v.Elem()) |
| 402 | } |
| 403 | case reflect.String: |
| 404 | return encodeString |
| 405 | default: |
| 406 | return nil |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | func encodeBool(v reflect.Value) string { |
| 411 | return strconv.FormatBool(v.Bool()) |
| 412 | } |
| 413 | |
| 414 | func encodeInt(v reflect.Value) string { |
| 415 | return utils.FormatInt(v.Int()) |
| 416 | } |
| 417 | |
| 418 | func encodeUint(v reflect.Value) string { |
| 419 | return utils.FormatUint(v.Uint()) |
| 420 | } |
| 421 | |
| 422 | func encodeFloat(v reflect.Value, bits int) string { |
| 423 | return strconv.FormatFloat(v.Float(), 'f', 6, bits) |
| 424 | } |
| 425 | |
| 426 | func encodeFloat32(v reflect.Value) string { |
| 427 | return encodeFloat(v, 32) |
| 428 | } |
| 429 | |
| 430 | func encodeFloat64(v reflect.Value) string { |
| 431 | return encodeFloat(v, 64) |
| 432 | } |
| 433 | |
| 434 | func encodeString(v reflect.Value) string { |
| 435 | return v.String() |
| 436 | } |