Skip to content

Commit

Permalink
Decode into non-nil pointer's existing value.
Browse files Browse the repository at this point in the history
Slight adaptation of Ian Remmler <[email protected]>'s fix in pr hashicorp#39:

> If decoding into a pointer, and the pointer points to a value, decode
> into the exitsing value.  Otherwise, decode into a new value and point
> to it.
> Addresses issue hashicorp#38.
  • Loading branch information
langmartin committed Apr 25, 2019
1 parent f5f70d6 commit c22487c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
5 changes: 5 additions & 0 deletions decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ func (d *decoder) decodeMap(name string, node ast.Node, result reflect.Value) er
}

func (d *decoder) decodePtr(name string, node ast.Node, result reflect.Value) error {
// if pointer is not nil, decode into existing value
if !result.IsNil() {
return d.decode(name, node, result.Elem())
}

// Create an element of the concrete (non pointer) type and decode
// into that. Then set the value of the pointer to this type.
resultType := result.Type()
Expand Down
29 changes: 29 additions & 0 deletions decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,35 @@ func TestDecode_structurePtr(t *testing.T) {
}
}

func TestDecode_nonNilStructurePtr(t *testing.T) {
type V struct {
Key int
Foo string
DontChange string
}

actual := &V{
Key: 42,
Foo: "foo",
DontChange: "don't change me",
}

err := Decode(&actual, testReadFile(t, "flat.hcl"))
if err != nil {
t.Fatalf("err: %s", err)
}

expected := &V{
Key: 7,
Foo: "bar",
DontChange: "don't change me",
}

if !reflect.DeepEqual(actual, expected) {
t.Fatalf("Actual: %#v\n\nExpected: %#v", actual, expected)
}
}

func TestDecode_structureArray(t *testing.T) {
// This test is extracted from a failure in Consul (consul.io),
// hence the interesting structure naming.
Expand Down

0 comments on commit c22487c

Please sign in to comment.