diff --git a/pdata/pcommon/map.go b/pdata/pcommon/map.go index 5bbfab962b0..91b803922a3 100644 --- a/pdata/pcommon/map.go +++ b/pdata/pcommon/map.go @@ -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() diff --git a/pdata/pcommon/map_test.go b/pdata/pcommon/map_test.go index a60d650fdc0..c3eafb25acd 100644 --- a/pdata/pcommon/map_test.go +++ b/pdata/pcommon/map_test.go @@ -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)