Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix UnmarshalTOML is not called when its underlying type is an array #870

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -1017,6 +1017,15 @@ func (d *Decoder) valueFromToml(mtype reflect.Type, tval interface{}, mval1 *ref
return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to trees", tval, tval)
case []interface{}:
d.visitor.visit()

// Check if pointer to value implements the Unmarshaler interface.
if mvalPtr := reflect.New(mtype); isCustomUnmarshaler(mvalPtr.Type()) {
if err := callCustomUnmarshaler(mvalPtr, tval); err != nil {
return reflect.ValueOf(nil), fmt.Errorf("unmarshal toml: %v", err)
}
return mvalPtr.Elem(), nil
}

if isOtherSequence(mtype) {
return d.valueFromOtherSlice(mtype, t)
}
Expand Down
43 changes: 43 additions & 0 deletions marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3864,6 +3864,49 @@ func TestCustomUnmarshalError(t *testing.T) {
}
}

type laxStringArray []string

func (c *laxStringArray) UnmarshalTOML(v interface{}) error {
switch val := v.(type) {
case []interface{}:
for _, v := range val {
switch v.(type) {
case string:
*c = append(*c, v.(string))
case int64:
*c = append(*c, strconv.FormatInt(v.(int64), 10))
default:
return fmt.Errorf("type assertion error: want string or int64, have %T", v)
}
}
return nil
}

return fmt.Errorf("type assertion error: want []interface{}, have %T", v)
}

type laxStringArrayStruct struct {
Array laxStringArray
ArrayPointer *laxStringArray
}

func TestCustomUnmarshalArray(t *testing.T) {
input := `
Array = [1]
ArrayPointer = [1]
`
var d laxStringArrayStruct
if err := Unmarshal([]byte(input), &d); err != nil {
t.Fatalf("unexpected err: %s", err.Error())
}
if len(d.Array) != 1 || d.Array[0] != "1" {
t.Errorf("Bad unmarshal: expected [1], got %v", d.Array)
}
if d.ArrayPointer == nil || len(*d.ArrayPointer) != 1 || (*d.ArrayPointer)[0] != "1" {
t.Errorf("Bad unmarshal: expected [1], got %v", d.ArrayPointer)
}
}

type intWrapper struct {
Value int
}
Expand Down