Debian Codegraph @

pdata/xpdata/map_builder.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package xpdata // import "go.opentelemetry.io/collector/pdata/xpdata"
5
6 import (
7 "go.opentelemetry.io/collector/pdata/internal"
8 "go.opentelemetry.io/collector/pdata/pcommon"
9 )
10
11 // MapBuilder is an experimental struct which can be used to create a pcommon.Map more efficiently
12 // than by repeated use of the Put family of methods, which check for duplicate keys on every call
13 // (a linear time operation).
14 // A zero-initialized MapBuilder is ready for use.
15 type MapBuilder struct {
16 state internal.State
17 pairs []internal.KeyValue
18 }
19
20 // EnsureCapacity increases the capacity of this MapBuilder instance, if necessary,
21 // to ensure that it can hold at least the number of elements specified by the capacity argument.
22 func (mb *MapBuilder) EnsureCapacity(capacity int) {
23 oldValues := mb.pairs
24 if capacity <= cap(oldValues) {
25 return
26 }
27 mb.pairs = make([]internal.KeyValue, len(oldValues), capacity)
28 copy(mb.pairs, oldValues)
29 }
30
31 func (mb *MapBuilder) getValue(i int) pcommon.Value {
32 return pcommon.Value(internal.NewValueWrapper(&mb.pairs[i].Value, &mb.state))
33 }
34
35 // AppendEmpty appends a key/value pair to the MapBuilder and return the inserted value.
36 // This method does not check for duplicate keys and has an amortized constant time complexity.
37 func (mb *MapBuilder) AppendEmpty(k string) pcommon.Value {
38 mb.pairs = append(mb.pairs, internal.KeyValue{Key: k})
39 return mb.getValue(len(mb.pairs) - 1)
40 }
41
42 // UnsafeIntoMap transfers the contents of a MapBuilder into a MapWrapper, without checking for duplicate keys.
43 // If the MapBuilder contains duplicate keys, the behavior of the resulting MapWrapper is unspecified.
44 // This operation has constant time complexity and makes no allocations.
45 // After this operation, the MapBuilder is reset to an empty state.
46 func (mb *MapBuilder) UnsafeIntoMap(m pcommon.Map) {
47 internal.GetMapState(internal.MapWrapper(m)).AssertMutable()
48 *internal.GetMapOrig(internal.MapWrapper(m)) = mb.pairs
49 mb.pairs = nil
50 }