Skip to content

Commit

Permalink
fix copy on append bug in reflection
Browse files Browse the repository at this point in the history
  • Loading branch information
oligon-fvs authored and dhubler committed Dec 19, 2023
1 parent 1294361 commit a20fcff
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
6 changes: 5 additions & 1 deletion nodeutil/reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,9 @@ func (self Reflect) listSlice(v reflect.Value, onChange OnListValueChange) node.
onChange(v)
}
entries = nil
return self.child(item), key, nil
// append() copies item to array, so we need to find new item in array and make further operations on it
appendedItem := v.Index(v.Len() - 1)
return self.child(appendedItem), key, nil
} else if key != nil {
if entries == nil {
var err error
Expand Down Expand Up @@ -454,6 +456,8 @@ func (self Reflect) create(t reflect.Type, m meta.Meta) reflect.Value {
return reflect.MakeMap(t)
case reflect.Slice:
return reflect.MakeSlice(t, 0, 0)
case reflect.Struct:
return reflect.New(t).Elem()
}
panic(fmt.Sprintf("creating type not supported %v", t))
}
Expand Down
30 changes: 27 additions & 3 deletions nodeutil/reflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ func TestReflect2Write(t *testing.T) {
fc.RequireEqual(t, nil, sel.Delete())
fc.AssertEqual(t, 0, len(app.Birds))
}
// slice(list) / structs
// slice(list) / pointer to structs
{
app := struct {
Birds []*testdata.Bird
Expand All @@ -248,6 +248,30 @@ func TestReflect2Write(t *testing.T) {
write(n, m2, `{"birds":[{"name":"robin","species":{"name":"DC Comics"}}]}`)
fc.AssertEqual(t, "DC Comics", app.Birds[0].Species.Name)

// delete
sel, err := b.Root().Find("birds=robin")
fc.RequireEqual(t, nil, err)
fc.RequireEqual(t, true, sel != nil)
fc.RequireEqual(t, nil, sel.Delete())
fc.AssertEqual(t, 0, len(app.Birds))
}
// slice(list) / structs
{
app := struct {
Birds []testdata.Bird
}{}
n := nodeutil.ReflectChild(&app)
write(n, m2, `{"birds":[{"name":"robin","species":{"name":"thrush"}}]}`)
if len(app.Birds) != 1 {
t.Fail()
}
fc.AssertEqual(t, "robin", app.Birds[0].Name)
fc.AssertEqual(t, "thrush", app.Birds[0].Species.Name)

// update
write(n, m2, `{"birds":[{"name":"robin","species":{"name":"DC Comics"}}]}`)
fc.AssertEqual(t, "DC Comics", app.Birds[0].Species.Name)

// delete
sel, err := b.Root().Find("birds=robin")
fc.RequireEqual(t, nil, err)
Expand Down Expand Up @@ -531,7 +555,7 @@ func TestCollectionNonStringKey(t *testing.T) {
mstr := `module m {
namespace "";
prefix "";
revision 0;
revision 0;
list x {
key id;
leaf id {
Expand All @@ -540,7 +564,7 @@ func TestCollectionNonStringKey(t *testing.T) {
leaf data {
type string;
}
}
}
}`
m, err := parser.LoadModuleFromString(nil, mstr)
if err != nil {
Expand Down

0 comments on commit a20fcff

Please sign in to comment.