Debian Codegraph @

encoder.go

raw
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 // freshKeys reports that encoding a value of this type into an empty map
54 // writes every key exactly once: no two fields share a name, and no field
55 // is recursed into — a nested struct's keys land in the same map, without
56 // a prefix, so they could collide with these. encode can then assign each
57 // key outright instead of reading it back to append.
58 freshKeys bool
59 }
60
61 // encField is the precomputed encoding plan for one struct field.
62 type encField struct {
63 name string
64 enc encoderFunc // immediate encoder; nil for structs and slices
65 elemEnc encoderFunc // slice element encoder, when the field is a slice
66 idx int
67 omitEmpty bool
68 // recurseStructPtr marks pointer-to-struct fields without a custom
69 // encoder: non-nil values are encoded by recursing into the element.
70 recurseStructPtr bool
71 // scratchSafe marks fields whose encoder output is allocated by this
72 // package (numeric/bool/float formatters), so it can never alias a large
73 // caller-owned buffer and may be batched in encode's shared scratch.
74 scratchSafe bool
75 // hasIsZero marks a struct-typed field whose type decides omitempty for
76 // itself through an IsZero method. Settling that here keeps the check off
77 // reflect.Value.Interface, which copies the struct to the heap every time
78 // it is asked — whether or not the method is there.
79 hasIsZero bool
80 isStruct bool
81 // nilAsNull marks pointer fields whose element has no immediate
82 // encoder (structs recursed via recurseStructPtr, or unsupported
83 // types): nil values encode as "null", matching the closure behavior
84 // pointer fields with encodable elements get.
85 nilAsNull bool
86 // elemPtrNil marks slice fields whose element is a pointer type with no
87 // encoder (e.g. []*Struct): nil elements encode as "null" (as they did
88 // historically), while a non-nil such element is an error.
89 elemPtrNil bool
90 }
91
92 // NewEncoder returns a new Encoder with defaults.
93 func NewEncoder() *Encoder {
94 return &Encoder{cache: newCache(), regenc: make(map[reflect.Type]encoderFunc)}
95 }
96
97 // Encode encodes a struct into map[string][]string.
98 //
99 // Intended for use with url.Values.
100 func (e *Encoder) Encode(src interface{}, dst map[string][]string) (err error) {
101 if dst == nil {
102 return errNilDst
103 }
104
105 // Catch panics from reflection or user-registered encoders and return
106 // them as an error instead of crashing the caller, mirroring Decode.
107 defer func() {
108 if r := recover(); r != nil {
109 if e, ok := r.(error); ok {
110 err = e
111 } else {
112 err = fmt.Errorf("schema: panic while encoding: %v", r)
113 }
114 }
115 }()
116
117 v := reflect.ValueOf(src)
118
119 return e.encode(v, dst)
120 }
121
122 // RegisterEncoder registers a converter for encoding a custom type.
123 func (e *Encoder) RegisterEncoder(value interface{}, encoder func(reflect.Value) string) {
124 e.cache.l.Lock()
125 e.regenc[reflect.TypeOf(value)] = encoder
126 e.cache.l.Unlock()
127 e.encGen.Add(1)
128 e.encCache.Clear()
129 }
130
131 // SetAliasTag changes the tag used to locate custom field aliases.
132 // The default tag is "schema".
133 func (e *Encoder) SetAliasTag(tag string) {
134 e.cache.l.Lock()
135 e.cache.tag = tag
136 e.cache.l.Unlock()
137 e.encGen.Add(1)
138 e.encCache.Clear()
139 }
140
141 // structInfo returns the cached encoding plan for struct type t, building it
142 // on first use. The build reads the tag and registered encoders under the
143 // configuration lock; the generation re-checks around the cache store keep a
144 // build racing a reconfiguration from inserting a stale plan.
145 func (e *Encoder) structInfo(t reflect.Type) (fields []encField, freshKeys bool) { //nolint:nonamedreturns // the bool is only readable named
146 gen := e.encGen.Load()
147 if cached, ok := e.encCache.Load(t); ok {
148 // Ignore plans built under an older configuration; fall through and
149 // rebuild (the fresh plan overwrites the stale entry).
150 if p := cached.(*encPlan); p.gen == gen {
151 return p.fields, p.freshKeys
152 }
153 }
154 e.cache.l.RLock()
155 tag := e.cache.tag
156 fields = make([]encField, 0, t.NumField())
157 for i := 0; i < t.NumField(); i++ {
158 sf := t.Field(i)
159 name, opts := fieldAlias(sf, tag)
160 if name == "-" {
161 continue
162 }
163 ft := sf.Type
164 f := encField{
165 idx: i,
166 name: name,
167 omitEmpty: opts.Contains("omitempty"),
168 recurseStructPtr: ft.Kind() == reflect.Ptr &&
169 ft.Elem().Kind() == reflect.Struct &&
170 !e.hasCustomEncoder(ft),
171 enc: typeEncoder(ft, e.regenc),
172 scratchSafe: scratchSafeEncoder(ft, e.regenc),
173 hasIsZero: ft.Kind() == reflect.Struct && ft.Implements(zeroerType),
174 }
175 if f.enc == nil {
176 switch ft.Kind() {
177 case reflect.Struct:
178 f.isStruct = true
179 case reflect.Slice:
180 f.elemEnc = typeEncoder(ft.Elem(), e.regenc)
181 if f.elemEnc == nil && ft.Elem().Kind() == reflect.Ptr {
182 f.elemPtrNil = true
183 }
184 case reflect.Ptr:
185 f.nilAsNull = true
186 }
187 }
188 fields = append(fields, f)
189 }
190 e.cache.l.RUnlock()
191 freshKeys = writesEachKeyOnce(fields)
192 // Don't cache a plan whose inputs (tag, registered encoders) changed
193 // while it was being built; the next call rebuilds it fresh. Even if a
194 // stale plan slips in after the clear, its generation tag keeps it from
195 // ever being served.
196 if e.encGen.Load() == gen {
197 e.encCache.Store(t, &encPlan{fields: fields, gen: gen, freshKeys: freshKeys})
198 }
199 return fields, freshKeys
200 }
201
202 // writesEachKeyOnce reports whether the plan's fields write distinct keys and
203 // none recurses into a nested struct, whose keys land in the same map and
204 // could repeat one of these.
205 func writesEachKeyOnce(fields []encField) bool {
206 names := make(map[string]struct{}, len(fields))
207 for i := range fields {
208 f := &fields[i]
209 if f.isStruct || f.recurseStructPtr {
210 return false
211 }
212 if _, dup := names[f.name]; dup {
213 return false
214 }
215 names[f.name] = struct{}{}
216 }
217 return true
218 }
219
220 // zeroer is the optional method a type can provide to decide, for omitempty,
221 // whether a value of it counts as empty.
222 type zeroer interface{ IsZero() bool }
223
224 var zeroerType = reflect.TypeFor[zeroer]()
225
226 // isZeroValue applies omitempty to one of this field's values: isZero with
227 // the struct case answered from the plan, so neither outcome goes through
228 // reflect.Value.Interface. An addressable struct becomes an interface through
229 // its address, without a copy, and a type known to lack IsZero skips the
230 // conversion altogether.
231 func (f *encField) isZeroValue(v reflect.Value) bool {
232 if v.Kind() != reflect.Struct || !v.CanInterface() {
233 return isZero(v)
234 }
235 if f.hasIsZero {
236 if v.CanAddr() {
237 // A value receiver's IsZero is in the pointer's method set too.
238 iz, _ := reflect.TypeAssert[zeroer](v.Addr())
239 return iz.IsZero()
240 }
241 iz, _ := reflect.TypeAssert[zeroer](v)
242 return iz.IsZero()
243 }
244 for i := 0; i < v.NumField(); i++ {
245 if !isZero(v.Field(i)) {
246 return false
247 }
248 }
249 return true
250 }
251
252 func isZero(v reflect.Value) bool {
253 switch v.Kind() {
254 case reflect.Func:
255 case reflect.Map, reflect.Slice:
256 return v.IsNil() || v.Len() == 0
257 case reflect.Array:
258 for i := 0; i < v.Len(); i++ {
259 if !isZero(v.Index(i)) {
260 return false
261 }
262 }
263 return true
264 case reflect.Struct:
265 if v.CanInterface() {
266 if iz, ok := v.Interface().(interface{ IsZero() bool }); ok {
267 return iz.IsZero()
268 }
269 }
270 for i := 0; i < v.NumField(); i++ {
271 if !isZero(v.Field(i)) {
272 return false
273 }
274 }
275 return true
276 }
277 // Compare other types directly:
278 return v.IsZero()
279 }
280
281 func (e *Encoder) encode(v reflect.Value, dst map[string][]string) error {
282 if v.Kind() == reflect.Ptr {
283 v = v.Elem()
284 }
285 if v.Kind() != reflect.Struct {
286 return errNotStruct
287 }
288
289 var errs MultiError
290
291 fields, freshKeys := e.structInfo(v.Type())
292 // When dst starts empty (fresh url.Values), single short package-allocated
293 // values of distinct keys share one backing array instead of allocating a
294 // 1-element slice each; the three-index slice caps entries so later
295 // appends cannot overwrite a neighbor. Caller-derived strings (string
296 // fields, custom encoders) and long values get their own independently
297 // collectible slice so a surviving entry cannot keep a deleted neighbor's
298 // allocation alive; a non-empty dst keeps the single-map-op append pattern.
299 useScratch := len(dst) == 0
300 // An empty dst plus a plan that writes every key once means each key is
301 // new, so the read append needs — a second hash of the key — is skipped.
302 fresh := useScratch && freshKeys
303 var scratch []string
304 appendValue := func(name, s string, scratchSafe bool) {
305 if !useScratch || !scratchSafe || len(s) > maxScratchValueLen {
306 if fresh {
307 dst[name] = []string{s}
308 return
309 }
310 dst[name] = append(dst[name], s)
311 return
312 }
313 if !fresh {
314 if old := dst[name]; old != nil {
315 dst[name] = append(old, s)
316 return
317 }
318 }
319 if scratch == nil {
320 scratch = make([]string, 0, len(fields))
321 }
322 scratch = append(scratch, s)
323 dst[name] = scratch[len(scratch)-1 : len(scratch) : len(scratch)]
324 }
325 for i := range fields {
326 f := &fields[i]
327 fieldValue := v.Field(f.idx)
328
329 // Encode struct pointer types if the field is a valid pointer and a struct.
330 if f.recurseStructPtr && !fieldValue.IsNil() {
331 if err := e.encode(fieldValue.Elem(), dst); err != nil {
332 errs = setError(errs, fieldValue.Elem().Type().String(), err)
333 }
334 continue
335 }
336
337 // Encode non-slice types and custom implementations immediately.
338 if f.enc != nil {
339 if f.omitEmpty && f.isZeroValue(fieldValue) {
340 continue
341 }
342 appendValue(f.name, f.enc(fieldValue), f.scratchSafe)
343 continue
344 }
345
346 if f.nilAsNull && fieldValue.IsNil() {
347 if f.omitEmpty {
348 continue
349 }
350 // The "null" literal is static data; always scratch-safe.
351 appendValue(f.name, "null", true)
352 continue
353 }
354
355 if f.isStruct {
356 if err := e.encode(fieldValue, dst); err != nil {
357 errs = setError(errs, fieldValue.Type().String(), err)
358 }
359 continue
360 }
361
362 // A non-slice field with no encoder (map, chan, array, or a non-nil
363 // pointer to an unencodable type), or a slice whose element type is
364 // itself unencodable and not a pointer (e.g. []Struct), cannot be
365 // encoded — historically this errored unconditionally.
366 if fieldValue.Kind() != reflect.Slice || (f.elemEnc == nil && !f.elemPtrNil) {
367 errs = setError(errs, fieldValue.Type().String(), fmt.Errorf("schema: encoder not found for %v", fieldValue))
368 continue
369 }
370
371 // Encode a slice. An empty slice has nothing to encode, so it is
372 // skipped under omitempty (and otherwise emitted empty).
373 n := fieldValue.Len()
374 if n == 0 && f.omitEmpty {
375 continue
376 }
377
378 values := make([]string, n)
379 if f.elemEnc == nil {
380 // Pointer elements with no encoder (elemPtrNil): nil encodes as
381 // "null" (as historically), a non-nil such element is an error.
382 bad := false
383 for j := 0; j < n; j++ {
384 if fieldValue.Index(j).IsNil() {
385 values[j] = "null"
386 continue
387 }
388 errs = setError(errs, fieldValue.Type().String(), fmt.Errorf("schema: encoder not found for %v", fieldValue))
389 bad = true
390 break
391 }
392 if bad {
393 continue
394 }
395 } else {
396 for j := 0; j < n; j++ {
397 values[j] = f.elemEnc(fieldValue.Index(j))
398 }
399 }
400 dst[f.name] = values
401 }
402
403 if len(errs) > 0 {
404 return errs
405 }
406 return nil
407 }
408
409 // setError lazily allocates m and stores err under key, overwriting any
410 // previous entry (matching the historical encoder error semantics).
411 func setError(m MultiError, key string, err error) MultiError {
412 if m == nil {
413 m = make(MultiError)
414 }
415 m[key] = err
416 return m
417 }
418
419 func (e *Encoder) hasCustomEncoder(t reflect.Type) bool {
420 _, exists := e.regenc[t]
421 return exists
422 }
423
424 // scratchSafeEncoder reports whether typeEncoder(t, reg)'s output strings are
425 // always allocated by this package's own formatters: string fields return the
426 // caller's string and custom encoders may return anything — either could be a
427 // small substring aliasing a large buffer, so neither may enter the scratch.
428 func scratchSafeEncoder(t reflect.Type, reg map[reflect.Type]encoderFunc) bool {
429 if _, ok := reg[t]; ok {
430 return false
431 }
432 switch t.Kind() {
433 case reflect.Bool,
434 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
435 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
436 reflect.Float32, reflect.Float64:
437 return true
438 case reflect.Ptr:
439 return scratchSafeEncoder(t.Elem(), reg)
440 default:
441 return false
442 }
443 }
444
445 func typeEncoder(t reflect.Type, reg map[reflect.Type]encoderFunc) encoderFunc {
446 if f, ok := reg[t]; ok {
447 return f
448 }
449
450 switch t.Kind() {
451 case reflect.Bool:
452 return encodeBool
453 case reflect.Int8:
454 return encodeInt8
455 case reflect.Int16:
456 return encodeInt16
457 case reflect.Int32:
458 return encodeInt32
459 case reflect.Int, reflect.Int64:
460 return encodeInt
461 case reflect.Uint8:
462 return encodeUint8
463 case reflect.Uint16:
464 return encodeUint16
465 case reflect.Uint32:
466 return encodeUint32
467 case reflect.Uint, reflect.Uint64:
468 return encodeUint
469 case reflect.Float32:
470 return encodeFloat32
471 case reflect.Float64:
472 return encodeFloat64
473 case reflect.Ptr:
474 f := typeEncoder(t.Elem(), reg)
475 if f == nil {
476 // No encoder for the element: report unsupported instead of
477 // returning a closure that would panic on non-nil values.
478 // Nil handling for such fields is done by encField.nilAsNull.
479 return nil
480 }
481 return func(v reflect.Value) string {
482 if v.IsNil() {
483 return "null"
484 }
485 return f(v.Elem())
486 }
487 case reflect.String:
488 return encodeString
489 default:
490 return nil
491 }
492 }
493
494 func encodeBool(v reflect.Value) string {
495 return strconv.FormatBool(v.Bool())
496 }
497
498 // Integers go through the width-specific utils helpers: the 8-bit ones are
499 // table lookups, allocating nothing, and the 32-bit ones skip a digit group
500 // the 64-bit formatter has to consider.
501
502 func encodeInt(v reflect.Value) string {
503 return utils.FormatInt(v.Int())
504 }
505
506 func encodeInt8(v reflect.Value) string {
507 return utils.FormatInt8(int8(v.Int()))
508 }
509
510 func encodeInt16(v reflect.Value) string {
511 return utils.FormatInt16(int16(v.Int()))
512 }
513
514 func encodeInt32(v reflect.Value) string {
515 return utils.FormatInt32(int32(v.Int()))
516 }
517
518 func encodeUint(v reflect.Value) string {
519 return utils.FormatUint(v.Uint())
520 }
521
522 func encodeUint8(v reflect.Value) string {
523 return utils.FormatUint8(uint8(v.Uint()))
524 }
525
526 func encodeUint16(v reflect.Value) string {
527 return utils.FormatUint16(uint16(v.Uint()))
528 }
529
530 func encodeUint32(v reflect.Value) string {
531 return utils.FormatUint32(uint32(v.Uint()))
532 }
533
534 func encodeFloat(v reflect.Value, bits int) string {
535 return formatFloatFixed(v.Float(), bits)
536 }
537
538 func encodeFloat32(v reflect.Value) string {
539 return encodeFloat(v, 32)
540 }
541
542 func encodeFloat64(v reflect.Value) string {
543 return encodeFloat(v, 64)
544 }
545
546 func encodeString(v reflect.Value) string {
547 return v.String()
548 }