Skip to content

Commit

Permalink
[pdata]: Add support to MoveTo for Map, allow avoiding copies
Browse files Browse the repository at this point in the history
Signed-off-by: Bogdan Drutu <[email protected]>
  • Loading branch information
bogdandrutu committed Sep 14, 2024
1 parent 8a07009 commit 6a0f4ac
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
9 changes: 9 additions & 0 deletions pdata/pcommon/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,15 @@ func (m Map) Range(f func(k string, v Value) bool) {
}
}

// MoveTo moves all key/values from the current map overriding the destination and
// resetting the current instance to its zero value
func (m Map) MoveTo(dest Map) {
m.getState().AssertMutable()
dest.getState().AssertMutable()
*dest.getOrig() = *m.getOrig()
*m.getOrig() = nil
}

// CopyTo copies all elements from the current map overriding the destination.
func (m Map) CopyTo(dest Map) {
dest.getState().AssertMutable()
Expand Down
19 changes: 18 additions & 1 deletion pdata/pcommon/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,11 +375,28 @@ func TestMap_FromRaw(t *testing.T) {
}, v.Map().AsRaw())
}

func TestMap_MoveTo(t *testing.T) {
dest := NewMap()
// Test MoveTo to empty
NewMap().MoveTo(dest)
assert.Equal(t, 0, dest.Len())

// Test MoveTo larger slice
src := Map(internal.GenerateTestMap())
src.MoveTo(dest)
assert.EqualValues(t, Map(internal.GenerateTestMap()), dest)
assert.Equal(t, 0, src.Len())

// Test MoveTo from empty to non-empty
NewMap().MoveTo(dest)
assert.Equal(t, 0, dest.Len())
}

func TestMap_CopyTo(t *testing.T) {
dest := NewMap()
// Test CopyTo to empty
NewMap().CopyTo(dest)
assert.EqualValues(t, 0, dest.Len())
assert.Equal(t, 0, dest.Len())

// Test CopyTo larger slice
Map(internal.GenerateTestMap()).CopyTo(dest)
Expand Down

0 comments on commit 6a0f4ac

Please sign in to comment.