Skip to content

Commit

Permalink
[pdata] Fix Map.EnsureCapacity bug when the Map is not empty (#8040)
Browse files Browse the repository at this point in the history
EnsureCapacity was incorrectly clearing the Map when increasing the
capacity. It will now correctly preserve existing elements.

---------

Co-authored-by: Alex Boten <alex@boten.ca>
  • Loading branch information
tigrannajaryan and codeboten committed Jul 7, 2023
1 parent 9375d95 commit 89e13a1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
6 changes: 3 additions & 3 deletions pdata/pcommon/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ func (m Map) Clear() {
// EnsureCapacity increases the capacity of this Map instance, if necessary,
// to ensure that it can hold at least the number of elements specified by the capacity argument.
func (m Map) EnsureCapacity(capacity int) {
if capacity <= cap(*m.getOrig()) {
oldOrig := *m.getOrig()
if capacity <= cap(oldOrig) {
return
}
oldOrig := *m.getOrig()
*m.getOrig() = make([]otlpcommon.KeyValue, 0, capacity)
*m.getOrig() = make([]otlpcommon.KeyValue, len(oldOrig), capacity)
copy(*m.getOrig(), oldOrig)
}

Expand Down
32 changes: 32 additions & 0 deletions pdata/pcommon/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,38 @@ func TestMap_EnsureCapacity(t *testing.T) {
assert.Equal(t, 8, cap(*am.getOrig()))
}

func TestMap_EnsureCapacity_Existing(t *testing.T) {
am := NewMap()
am.PutStr("foo", "bar")

assert.Equal(t, 1, am.Len())

// Add more capacity.
am.EnsureCapacity(5)

// Ensure previously existing element is still there.
assert.Equal(t, 1, am.Len())
v, ok := am.Get("foo")
assert.Equal(t, v.Str(), "bar")
assert.True(t, ok)

assert.Equal(t, 5, cap(*am.getOrig()))

// Add one more element.
am.PutStr("abc", "xyz")

// Verify that both elements are there.
assert.Equal(t, 2, am.Len())

v, ok = am.Get("foo")
assert.Equal(t, v.Str(), "bar")
assert.True(t, ok)

v, ok = am.Get("abc")
assert.Equal(t, v.Str(), "xyz")
assert.True(t, ok)
}

func TestMap_Clear(t *testing.T) {
am := NewMap()
assert.Nil(t, *am.getOrig())
Expand Down

0 comments on commit 89e13a1

Please sign in to comment.