| 1 | package schema |
| 2 | |
| 3 | import ( |
| 4 | "reflect" |
| 5 | "strings" |
| 6 | "testing" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | // Keys served by the direct-path map must behave exactly like the generic |
| 11 | // parser: case-insensitive, covering flat aliases and nested dotted chains. |
| 12 | func TestDirectPathLookup(t *testing.T) { |
| 13 | type Inner struct { |
| 14 | Value string `schema:"value"` |
| 15 | } |
| 16 | type Outer struct { |
| 17 | Name string `schema:"name"` |
| 18 | Nested Inner `schema:"nested"` |
| 19 | } |
| 20 | |
| 21 | for _, keys := range []struct { |
| 22 | name, nested string |
| 23 | }{ |
| 24 | {"name", "nested.value"}, |
| 25 | {"NAME", "NESTED.VALUE"}, |
| 26 | {"NaMe", "NeStEd.VaLuE"}, |
| 27 | } { |
| 28 | var s Outer |
| 29 | data := map[string][]string{ |
| 30 | keys.name: {"x"}, |
| 31 | keys.nested: {"y"}, |
| 32 | } |
| 33 | if err := NewDecoder().Decode(&s, data); err != nil { |
| 34 | t.Fatalf("Decode(%q, %q): %v", keys.name, keys.nested, err) |
| 35 | } |
| 36 | if s.Name != "x" || s.Nested.Value != "y" { |
| 37 | t.Fatalf("Decode(%q, %q) = %+v, want Name=x Nested.Value=y", keys.name, keys.nested, s) |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // Direct-path entries exist for statically-resolvable keys only; everything |
| 43 | // else must keep flowing through the generic parser unchanged. |
| 44 | func TestDirectPathLookupFallbacks(t *testing.T) { |
| 45 | // Keys longer than the case-fold buffer take the generic path. |
| 46 | longAlias := strings.Repeat("a", maxDirectKeyLen+8) |
| 47 | type Long struct { |
| 48 | Field string `schema:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"` |
| 49 | } |
| 50 | if len(longAlias) != maxDirectKeyLen+8 { |
| 51 | t.Fatal("bad test setup") |
| 52 | } |
| 53 | var l Long |
| 54 | if err := NewDecoder().Decode(&l, map[string][]string{longAlias: {"v"}}); err != nil { |
| 55 | t.Fatalf("long key: %v", err) |
| 56 | } |
| 57 | if l.Field != "v" { |
| 58 | t.Fatalf("long key decoded %+v", l) |
| 59 | } |
| 60 | |
| 61 | // A bare slice-of-structs alias still needs a slice index; the direct map |
| 62 | // must not make it valid. |
| 63 | type Item struct { |
| 64 | Value string `schema:"value"` |
| 65 | } |
| 66 | type WithItems struct { |
| 67 | Items []Item `schema:"items"` |
| 68 | } |
| 69 | var w WithItems |
| 70 | err := NewDecoder().Decode(&w, map[string][]string{"items": {"x"}}) |
| 71 | if err == nil { |
| 72 | t.Fatal("bare slice-of-structs alias must remain an invalid path") |
| 73 | } |
| 74 | if _, ok := err.(MultiError)["items"].(UnknownKeyError); !ok { |
| 75 | t.Fatalf("want UnknownKeyError, got %v", err) |
| 76 | } |
| 77 | |
| 78 | // Pointer-to-struct chains are not precomputed but must keep decoding. |
| 79 | type Inner struct { |
| 80 | Value string `schema:"value"` |
| 81 | } |
| 82 | type WithPtr struct { |
| 83 | Nested *Inner `schema:"nested"` |
| 84 | } |
| 85 | var p WithPtr |
| 86 | if err := NewDecoder().Decode(&p, map[string][]string{"NESTED.value": {"y"}}); err != nil { |
| 87 | t.Fatalf("pointer chain: %v", err) |
| 88 | } |
| 89 | if p.Nested == nil || p.Nested.Value != "y" { |
| 90 | t.Fatalf("pointer chain decoded %+v", p) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | // The native slice decode path must keep the generic path's semantics: comma |
| 95 | // splitting, zeroEmpty, all-or-nothing assignment, ConversionError details. |
| 96 | func TestNativeSliceDecode(t *testing.T) { |
| 97 | type S struct { |
| 98 | Tags []string `schema:"tags"` |
| 99 | IDs []int `schema:"ids"` |
| 100 | Scores []float64 `schema:"scores"` |
| 101 | Flags []bool `schema:"flags"` |
| 102 | Big []int64 `schema:"big"` |
| 103 | U []uint `schema:"u"` |
| 104 | U64 []uint64 `schema:"u64"` |
| 105 | } |
| 106 | |
| 107 | var s S |
| 108 | data := map[string][]string{ |
| 109 | "tags": {"a", "b,c", ""}, // strings never split on commas |
| 110 | "ids": {"1,2", "3"}, |
| 111 | "scores": {"1.5", "2.5"}, |
| 112 | "flags": {"true", "on"}, |
| 113 | "big": {"9007199254740993"}, |
| 114 | "u": {"7"}, |
| 115 | "u64": {"18446744073709551615"}, |
| 116 | } |
| 117 | if err := NewDecoder().Decode(&s, data); err != nil { |
| 118 | t.Fatal(err) |
| 119 | } |
| 120 | want := S{ |
| 121 | Tags: []string{"a", "b,c"}, |
| 122 | IDs: []int{1, 2, 3}, |
| 123 | Scores: []float64{1.5, 2.5}, |
| 124 | Flags: []bool{true, true}, |
| 125 | Big: []int64{9007199254740993}, |
| 126 | U: []uint{7}, |
| 127 | U64: []uint64{18446744073709551615}, |
| 128 | } |
| 129 | if !reflect.DeepEqual(s, want) { |
| 130 | t.Fatalf("got %+v, want %+v", s, want) |
| 131 | } |
| 132 | |
| 133 | // zeroEmpty appends zero values for empty items. |
| 134 | var z S |
| 135 | d := NewDecoder() |
| 136 | d.ZeroEmpty(true) |
| 137 | if err := d.Decode(&z, map[string][]string{"ids": {"1,,2", ""}}); err != nil { |
| 138 | t.Fatal(err) |
| 139 | } |
| 140 | if !reflect.DeepEqual(z.IDs, []int{1, 0, 2, 0}) { |
| 141 | t.Fatalf("zeroEmpty got %v", z.IDs) |
| 142 | } |
| 143 | |
| 144 | // A parse failure must leave the field untouched and carry the value's |
| 145 | // index in the ConversionError. |
| 146 | pre := S{IDs: []int{42}} |
| 147 | err := NewDecoder().Decode(&pre, map[string][]string{"ids": {"1", "oops"}}) |
| 148 | if err == nil { |
| 149 | t.Fatal("want conversion error") |
| 150 | } |
| 151 | convErr, ok := err.(MultiError)["ids"].(ConversionError) |
| 152 | if !ok { |
| 153 | t.Fatalf("want ConversionError, got %v", err) |
| 154 | } |
| 155 | if convErr.Index != 1 { |
| 156 | t.Fatalf("want Index=1, got %d", convErr.Index) |
| 157 | } |
| 158 | if !reflect.DeepEqual(pre.IDs, []int{42}) { |
| 159 | t.Fatalf("field must stay untouched on error, got %v", pre.IDs) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | // Named slice types take the generic reflect loop, not the native path; its |
| 164 | // semantics must match the native path's exactly. |
| 165 | func TestGenericSliceNamedTypes(t *testing.T) { |
| 166 | type IDs []int |
| 167 | type Tags []string |
| 168 | type S struct { |
| 169 | IDs IDs `schema:"ids"` |
| 170 | Tags Tags `schema:"tags"` |
| 171 | } |
| 172 | |
| 173 | var s S |
| 174 | data := map[string][]string{ |
| 175 | "ids": {"1,2", "3"}, |
| 176 | "tags": {"a", "b,c"}, |
| 177 | } |
| 178 | if err := NewDecoder().Decode(&s, data); err != nil { |
| 179 | t.Fatal(err) |
| 180 | } |
| 181 | if !reflect.DeepEqual(s.IDs, IDs{1, 2, 3}) || !reflect.DeepEqual(s.Tags, Tags{"a", "b,c"}) { |
| 182 | t.Fatalf("got %+v", s) |
| 183 | } |
| 184 | |
| 185 | // zeroEmpty fills zero slots; empties are dropped without it. |
| 186 | var z S |
| 187 | d := NewDecoder() |
| 188 | d.ZeroEmpty(true) |
| 189 | if err := d.Decode(&z, map[string][]string{"ids": {"1,,2", ""}}); err != nil { |
| 190 | t.Fatal(err) |
| 191 | } |
| 192 | if !reflect.DeepEqual(z.IDs, IDs{1, 0, 2, 0}) { |
| 193 | t.Fatalf("zeroEmpty got %v", z.IDs) |
| 194 | } |
| 195 | var trunc S |
| 196 | if err := NewDecoder().Decode(&trunc, map[string][]string{"ids": {"1,,2", ""}}); err != nil { |
| 197 | t.Fatal(err) |
| 198 | } |
| 199 | if !reflect.DeepEqual(trunc.IDs, IDs{1, 2}) { |
| 200 | t.Fatalf("truncation got %v", trunc.IDs) |
| 201 | } |
| 202 | |
| 203 | // Parse failures, both inside a comma list and as a plain value. |
| 204 | for _, bad := range []string{"1,x", "x"} { |
| 205 | var b S |
| 206 | err := NewDecoder().Decode(&b, map[string][]string{"ids": {bad}}) |
| 207 | if _, ok := err.(MultiError)["ids"].(ConversionError); !ok { |
| 208 | t.Fatalf("value %q: want ConversionError, got %v", bad, err) |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | // Fields the fast scalar path skips (pointers) keep their generic behavior. |
| 214 | func TestGenericScalarFallbacks(t *testing.T) { |
| 215 | type S struct { |
| 216 | N *int `schema:"n"` |
| 217 | } |
| 218 | |
| 219 | // Empty value + ZeroEmpty on a pointer field takes the generic zeroing. |
| 220 | d := NewDecoder() |
| 221 | d.ZeroEmpty(true) |
| 222 | var s S |
| 223 | if err := d.Decode(&s, map[string][]string{"n": {""}}); err != nil { |
| 224 | t.Fatal(err) |
| 225 | } |
| 226 | if s.N == nil || *s.N != 0 { |
| 227 | t.Fatalf("want zeroed *int, got %+v", s.N) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | // Encoding into a fresh dst must handle every appendValue branch: duplicate |
| 232 | // aliases appending to a scratch-backed entry, caller-derived strings and |
| 233 | // long formatter output bypassing the shared scratch, and short numeric |
| 234 | // values using it. |
| 235 | func TestEncodeDuplicateAliasFreshDst(t *testing.T) { |
| 236 | type S struct { |
| 237 | A int `schema:"k"` |
| 238 | B int `schema:"k"` |
| 239 | C string `schema:"c"` |
| 240 | L float64 `schema:"l"` |
| 241 | } |
| 242 | dst := map[string][]string{} |
| 243 | // 1e300 in 'f' format is far longer than maxScratchValueLen. |
| 244 | if err := NewEncoder().Encode(S{A: 1, B: 2, C: "3", L: 1e300}, dst); err != nil { |
| 245 | t.Fatal(err) |
| 246 | } |
| 247 | if !reflect.DeepEqual(dst["k"], []string{"1", "2"}) || !reflect.DeepEqual(dst["c"], []string{"3"}) { |
| 248 | t.Fatalf("got %v", dst) |
| 249 | } |
| 250 | if len(dst["l"]) != 1 || len(dst["l"][0]) <= maxScratchValueLen { |
| 251 | t.Fatalf("long value got %v", dst["l"]) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | type sliceHeavyStruct struct { |
| 256 | Tags []string `schema:"tags"` |
| 257 | IDs []int `schema:"ids"` |
| 258 | Scores []float64 `schema:"scores"` |
| 259 | Flags []bool `schema:"flags"` |
| 260 | } |
| 261 | |
| 262 | func BenchmarkSliceHeavyDecode(b *testing.B) { |
| 263 | data := map[string][]string{ |
| 264 | "tags": {"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi"}, |
| 265 | "ids": {"1,2,3,4,5,6,7,8", "9,10,11,12,13,14,15,16"}, |
| 266 | "scores": {"1.5", "2.5", "3.5", "4.5", "5.5", "6.5", "7.5", "8.5"}, |
| 267 | "flags": {"true", "false", "true", "false", "true", "false", "true", "false"}, |
| 268 | } |
| 269 | decoder := NewDecoder() |
| 270 | s := &sliceHeavyStruct{} |
| 271 | b.ReportAllocs() |
| 272 | for b.Loop() { |
| 273 | if err := decoder.Decode(s, data); err != nil { |
| 274 | b.Fatal(err) |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | type fan0 struct { |
| 280 | V string `schema:"v"` |
| 281 | } |
| 282 | type fan1 struct { |
| 283 | A fan0 `schema:"a"` |
| 284 | B fan0 `schema:"b"` |
| 285 | } |
| 286 | type fan2 struct { |
| 287 | A fan1 `schema:"a"` |
| 288 | B fan1 `schema:"b"` |
| 289 | } |
| 290 | type fan3 struct { |
| 291 | A fan2 `schema:"a"` |
| 292 | B fan2 `schema:"b"` |
| 293 | } |
| 294 | type fan4 struct { |
| 295 | A fan3 `schema:"a"` |
| 296 | B fan3 `schema:"b"` |
| 297 | } |
| 298 | type fan5 struct { |
| 299 | A fan4 `schema:"a"` |
| 300 | B fan4 `schema:"b"` |
| 301 | } |
| 302 | type fan6 struct { |
| 303 | A fan5 `schema:"a"` |
| 304 | B fan5 `schema:"b"` |
| 305 | } |
| 306 | type fan7 struct { |
| 307 | A fan6 `schema:"a"` |
| 308 | B fan6 `schema:"b"` |
| 309 | } |
| 310 | type fan8 struct { |
| 311 | A fan7 `schema:"a"` |
| 312 | B fan7 `schema:"b"` |
| 313 | } |
| 314 | type fan9 struct { |
| 315 | A fan8 `schema:"a"` |
| 316 | B fan8 `schema:"b"` |
| 317 | } |
| 318 | type fan10 struct { |
| 319 | A fan9 `schema:"a"` |
| 320 | B fan9 `schema:"b"` |
| 321 | } |
| 322 | type fan11 struct { |
| 323 | A fan10 `schema:"a"` |
| 324 | B fan10 `schema:"b"` |
| 325 | } |
| 326 | |
| 327 | // Deep fan-out nesting has exponentially many dotted paths; the direct map |
| 328 | // must stay capped so the first Decode neither stalls nor retains huge maps. |
| 329 | // Depth stays at 11 (2048 paths, 4x the cap): deeper trees blow up the Go 1.27 |
| 330 | // compiler, which flattens every leaf into a single generated equality func. |
| 331 | func TestDirectPathsCappedForDeepFanout(t *testing.T) { |
| 332 | d := NewDecoder() |
| 333 | var s fan11 |
| 334 | deepKey := strings.Repeat("a.", 6) + strings.Repeat("b.", 5) + "v" |
| 335 | data := map[string][]string{deepKey: {"deep"}} |
| 336 | done := make(chan error, 1) |
| 337 | go func() { done <- d.Decode(&s, data) }() |
| 338 | select { |
| 339 | case err := <-done: |
| 340 | if err != nil { |
| 341 | t.Fatal(err) |
| 342 | } |
| 343 | case <-time.After(30 * time.Second): |
| 344 | t.Fatal("Decode stalled: direct-path precomputation not capped") |
| 345 | } |
| 346 | if s.A.A.A.A.A.A.B.B.B.B.B.V != "deep" { |
| 347 | t.Fatal("deep key not decoded") |
| 348 | } |
| 349 | info := d.cache.get(reflect.TypeOf(s)) |
| 350 | if len(info.direct) > maxDirectPaths+2 { |
| 351 | t.Fatalf("direct map has %d entries, want <= %d", len(info.direct), maxDirectPaths+2) |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | // Unlike the other encode benchmarks, this one encodes into a fresh map each |
| 356 | // iteration, matching how callers build url.Values per request. |
| 357 | func BenchmarkEncodeFreshDst(b *testing.B) { |
| 358 | type S struct { |
| 359 | A string `schema:"a"` |
| 360 | B int `schema:"b"` |
| 361 | C bool `schema:"c"` |
| 362 | D float64 `schema:"d"` |
| 363 | E []int `schema:"e"` |
| 364 | F string `schema:"f,omitempty"` |
| 365 | } |
| 366 | s := S{A: "abc", B: 123, C: true, D: 3.14, E: []int{1, 2, 3}} |
| 367 | enc := NewEncoder() |
| 368 | b.ReportAllocs() |
| 369 | for b.Loop() { |
| 370 | vals := make(map[string][]string, 8) |
| 371 | if err := enc.Encode(&s, vals); err != nil { |
| 372 | b.Fatal(err) |
| 373 | } |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | func BenchmarkMixedCaseKeyDecode(b *testing.B) { |
| 378 | type S struct { |
| 379 | FirstName string `schema:"firstName"` |
| 380 | LastName string `schema:"lastName"` |
| 381 | Age int `schema:"age"` |
| 382 | } |
| 383 | data := map[string][]string{ |
| 384 | "FirstName": {"Grace"}, |
| 385 | "LASTNAME": {"Hopper"}, |
| 386 | "age": {"85"}, |
| 387 | } |
| 388 | decoder := NewDecoder() |
| 389 | s := &S{} |
| 390 | for b.Loop() { |
| 391 | if err := decoder.Decode(s, data); err != nil { |
| 392 | b.Fatal(err) |
| 393 | } |
| 394 | } |
| 395 | } |