|
| 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 | + otlpcommon "go.opentelemetry.io/collector/pdata/internal/data/protogen/common/v1" |
| 9 | + "go.opentelemetry.io/collector/pdata/pcommon" |
| 10 | +) |
| 11 | + |
| 12 | +// MapBuilder is an experimental struct which can be used to create a pcommon.Map more efficiently |
| 13 | +// than by repeated use of the Put family of methods, which check for duplicate keys on every call |
| 14 | +// (a linear time operation). |
| 15 | +// A zero-initialized MapBuilder is ready for use. |
| 16 | +type MapBuilder struct { |
| 17 | + state internal.State |
| 18 | + pairs []otlpcommon.KeyValue |
| 19 | +} |
| 20 | + |
| 21 | +// EnsureCapacity increases the capacity of this MapBuilder instance, if necessary, |
| 22 | +// to ensure that it can hold at least the number of elements specified by the capacity argument. |
| 23 | +func (mb *MapBuilder) EnsureCapacity(capacity int) { |
| 24 | + mb.state.AssertMutable() |
| 25 | + oldValues := mb.pairs |
| 26 | + if capacity <= cap(oldValues) { |
| 27 | + return |
| 28 | + } |
| 29 | + mb.pairs = make([]otlpcommon.KeyValue, len(oldValues), capacity) |
| 30 | + copy(mb.pairs, oldValues) |
| 31 | +} |
| 32 | + |
| 33 | +func (mb *MapBuilder) getValue(i int) pcommon.Value { |
| 34 | + return pcommon.Value(internal.NewValue(&mb.pairs[i].Value, &mb.state)) |
| 35 | +} |
| 36 | + |
| 37 | +// AppendEmpty appends a key/value pair to the MapBuilder and return the inserted value. |
| 38 | +// This method does not check for duplicate keys and has an amortized constant time complexity. |
| 39 | +func (mb *MapBuilder) AppendEmpty(k string) pcommon.Value { |
| 40 | + mb.state.AssertMutable() |
| 41 | + mb.pairs = append(mb.pairs, otlpcommon.KeyValue{Key: k}) |
| 42 | + return mb.getValue(len(mb.pairs) - 1) |
| 43 | +} |
| 44 | + |
| 45 | +// UnsafeIntoMap transfers the contents of a MapBuilder into a Map, without checking for duplicate keys. |
| 46 | +// If the MapBuilder contains duplicate keys, the behavior of the resulting Map is unspecified. |
| 47 | +// This operation has constant time complexity and makes no allocations. |
| 48 | +// After this operation, the MapBuilder becomes read-only. |
| 49 | +func (mb *MapBuilder) UnsafeIntoMap(m pcommon.Map) { |
| 50 | + mb.state.AssertMutable() |
| 51 | + internal.GetMapState(internal.Map(m)).AssertMutable() |
| 52 | + mb.state = internal.StateReadOnly // to avoid modifying a Map later marked as ReadOnly through builder Values |
| 53 | + *internal.GetOrigMap(internal.Map(m)) = mb.pairs |
| 54 | +} |
0 commit comments