fix(decode): report the smallest unknown field deterministically

Assisted-by: GLM 5.3
This commit is contained in:
2026-09-17 23:11:38 +02:00
parent 4def1b3e8b
commit 3c8ac859c0
4 changed files with 42 additions and 4 deletions
+16 -3
View File
@@ -107,12 +107,25 @@ func (d *decoder) assignTable(tbl map[string]any, dst reflect.Value) error {
func (d *decoder) assignStruct(tbl map[string]any, dst reflect.Value) error {
schema := cachedStructSchema(dst.Type())
if d.disallowUnknown {
// Map iteration order is random, so pick the unknown key to report
// deterministically: the smallest one.
unknown := ""
for key := range tbl {
if _, ok := schema.byName[strings.ToLower(key)]; ok {
continue
}
if unknown == "" || key < unknown {
unknown = key
}
}
if unknown != "" {
return fmt.Errorf("interpres: unknown field %q for %s", unknown, dst.Type())
}
}
for key, val := range tbl {
field, ok := schema.byName[strings.ToLower(key)]
if !ok {
if d.disallowUnknown {
return fmt.Errorf("interpres: unknown field %q for %s", key, dst.Type())
}
if schema.embedMaps != nil {
// Leftover keys land in an untagged embedded map, the inverse
// of the encoder inlining that map's entries.