Skip to content

Commit

Permalink
fixed panic on pointers to embedded structs (#139)
Browse files Browse the repository at this point in the history
* fixed panic on pointers to embedded structs

* don't alloc when it's already allocated
  • Loading branch information
morus12 committed Aug 20, 2020
1 parent 61751c9 commit 0cfe0ec
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
11 changes: 11 additions & 0 deletions decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,17 @@ func (d *Decoder) decode(v reflect.Value, path string, parts []pathPart, values
}
v = v.Elem()
}

// alloc embedded structs
if v.Type().Kind() == reflect.Struct {
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
if field.Type().Kind() == reflect.Ptr && field.IsNil() && v.Type().Field(i).Anonymous == true {
field.Set(reflect.New(field.Type().Elem()))
}
}
}

v = v.FieldByName(name)
}
// Don't even bother for unexported fields.
Expand Down
39 changes: 39 additions & 0 deletions decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1985,3 +1985,42 @@ func TestTextUnmarshalerEmpty(t *testing.T) {
t.Errorf("Expected %v errors, got %v", expected, s.Value)
}
}

type S23n struct {
F2 string `schema:"F2"`
F3 string `schema:"F3"`
}

type S23e struct {
*S23n
F1 string `schema:"F1"`
}

type S23 []*S23e

func TestUnmashalPointerToEmbedded(t *testing.T) {
data := map[string][]string{
"A.0.F2": []string{"raw a"},
"A.0.F3": []string{"raw b"},
}

// Implements encoding.TextUnmarshaler, should not throw invalid path
// error.
s := struct {
Value S23 `schema:"A"`
}{}
decoder := NewDecoder()

if err := decoder.Decode(&s, data); err != nil {
t.Fatal("Error while decoding:", err)
}

expected := S23{
&S23e{
S23n: &S23n{"raw a", "raw b"},
},
}
if !reflect.DeepEqual(expected, s.Value) {
t.Errorf("Expected %v errors, got %v", expected, s.Value)
}
}

0 comments on commit 0cfe0ec

Please sign in to comment.