Debian Codegraph @

pdata/pcommon/map.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package pcommon // import "go.opentelemetry.io/collector/pdata/pcommon"
5
6 import (
7 "iter"
8
9 "go.uber.org/multierr"
10
11 "go.opentelemetry.io/collector/pdata/internal"
12 )
13
14 // Map stores a map of string keys to elements of Value type.
15 //
16 // Must use NewMap function to create new instances.
17 // Important: zero-initialized instance is not valid for use.
18 type Map internal.MapWrapper
19
20 // NewMap creates a Map with 0 elements.
21 func NewMap() Map {
22 orig := []internal.KeyValue(nil)
23 return Map(internal.NewMapWrapper(&orig, internal.NewState()))
24 }
25
26 func (m Map) getOrig() *[]internal.KeyValue {
27 return internal.GetMapOrig(internal.MapWrapper(m))
28 }
29
30 func (m Map) getState() *internal.State {
31 return internal.GetMapState(internal.MapWrapper(m))
32 }
33
34 func newMap(orig *[]internal.KeyValue, state *internal.State) Map {
35 return Map(internal.NewMapWrapper(orig, state))
36 }
37
38 // Clear erases any existing entries in this Map instance.
39 func (m Map) Clear() {
40 m.getState().AssertMutable()
41 *m.getOrig() = nil
42 }
43
44 // EnsureCapacity increases the capacity of this Map instance, if necessary,
45 // to ensure that it can hold at least the number of elements specified by the capacity argument.
46 func (m Map) EnsureCapacity(capacity int) {
47 m.getState().AssertMutable()
48 oldOrig := *m.getOrig()
49 if capacity <= cap(oldOrig) {
50 return
51 }
52 *m.getOrig() = make([]internal.KeyValue, len(oldOrig), capacity)
53 copy(*m.getOrig(), oldOrig)
54 }
55
56 // Get returns the Value associated with the key and true. The returned
57 // Value is not a copy, it is a reference to the value stored in this map.
58 // It is allowed to modify the returned value using Value.Set* functions.
59 // Such modification will be applied to the value stored in this map.
60 // Accessing the returned value after modifying the underlying map
61 // (removing or adding new values) is an undefined behavior.
62 //
63 // If the key does not exist, returns a zero-initialized KeyValue and false.
64 // Calling any functions on the returned invalid instance may cause a panic.
65 func (m Map) Get(key string) (Value, bool) {
66 for i := range *m.getOrig() {
67 akv := &(*m.getOrig())[i]
68 if akv.Key == key {
69 return newValue(&akv.Value, m.getState()), true
70 }
71 }
72 return newValue(nil, m.getState()), false
73 }
74
75 // Remove removes the entry associated with the key and returns true if the key
76 // was present in the map, otherwise returns false.
77 func (m Map) Remove(key string) bool {
78 m.getState().AssertMutable()
79 for i := range *m.getOrig() {
80 akv := &(*m.getOrig())[i]
81 if akv.Key == key {
82 *akv = (*m.getOrig())[len(*m.getOrig())-1]
83 *m.getOrig() = (*m.getOrig())[:len(*m.getOrig())-1]
84 return true
85 }
86 }
87 return false
88 }
89
90 // RemoveIf removes the entries for which the function in question returns true
91 func (m Map) RemoveIf(f func(string, Value) bool) {
92 m.getState().AssertMutable()
93 newLen := 0
94 for i := 0; i < len(*m.getOrig()); i++ {
95 if f((*m.getOrig())[i].Key, newValue(&(*m.getOrig())[i].Value, m.getState())) {
96 (*m.getOrig())[i] = internal.KeyValue{}
97 continue
98 }
99 if newLen == i {
100 // Nothing to move, element is at the right place.
101 newLen++
102 continue
103 }
104 (*m.getOrig())[newLen] = (*m.getOrig())[i]
105 (*m.getOrig())[i] = internal.KeyValue{}
106 newLen++
107 }
108 *m.getOrig() = (*m.getOrig())[:newLen]
109 }
110
111 // PutEmpty inserts or updates an empty value to the map under given key
112 // and return the updated/inserted value.
113 func (m Map) PutEmpty(k string) Value {
114 m.getState().AssertMutable()
115 if av, existing := m.Get(k); existing {
116 av.getOrig().Value = nil
117 return newValue(av.getOrig(), m.getState())
118 }
119 *m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k})
120 return newValue(&(*m.getOrig())[len(*m.getOrig())-1].Value, m.getState())
121 }
122
123 // GetOrPutEmpty returns the Value associated with the key and true (loaded) if the key exists in the map,
124 // otherwise inserts an empty value to the map under the given key and returns the inserted value
125 // and false (loaded).
126 func (m Map) GetOrPutEmpty(k string) (Value, bool) {
127 m.getState().AssertMutable()
128 if av, existing := m.Get(k); existing {
129 return av, true
130 }
131 *m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k})
132 return newValue(&(*m.getOrig())[len(*m.getOrig())-1].Value, m.getState()), false
133 }
134
135 // PutStr performs the Insert or Update action. The Value is
136 // inserted to the map that did not originally have the key. The key/value is
137 // updated to the map where the key already existed.
138 func (m Map) PutStr(k, v string) {
139 m.getState().AssertMutable()
140 if av, existing := m.Get(k); existing {
141 av.SetStr(v)
142 return
143 }
144 ov := internal.NewAnyValueStringValue()
145 ov.StringValue = v
146 *m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
147 }
148
149 // PutInt performs the Insert or Update action. The int Value is
150 // inserted to the map that did not originally have the key. The key/value is
151 // updated to the map where the key already existed.
152 func (m Map) PutInt(k string, v int64) {
153 m.getState().AssertMutable()
154 if av, existing := m.Get(k); existing {
155 av.SetInt(v)
156 return
157 }
158 ov := internal.NewAnyValueIntValue()
159 ov.IntValue = v
160 *m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
161 }
162
163 // PutDouble performs the Insert or Update action. The double Value is
164 // inserted to the map that did not originally have the key. The key/value is
165 // updated to the map where the key already existed.
166 func (m Map) PutDouble(k string, v float64) {
167 m.getState().AssertMutable()
168 if av, existing := m.Get(k); existing {
169 av.SetDouble(v)
170 return
171 }
172 ov := internal.NewAnyValueDoubleValue()
173 ov.DoubleValue = v
174 *m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
175 }
176
177 // PutBool performs the Insert or Update action. The bool Value is
178 // inserted to the map that did not originally have the key. The key/value is
179 // updated to the map where the key already existed.
180 func (m Map) PutBool(k string, v bool) {
181 m.getState().AssertMutable()
182 if av, existing := m.Get(k); existing {
183 av.SetBool(v)
184 return
185 }
186 ov := internal.NewAnyValueBoolValue()
187 ov.BoolValue = v
188 *m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
189 }
190
191 // PutEmptyBytes inserts or updates an empty byte slice under given key and returns it.
192 func (m Map) PutEmptyBytes(k string) ByteSlice {
193 m.getState().AssertMutable()
194 if av, existing := m.Get(k); existing {
195 return av.SetEmptyBytes()
196 }
197 ov := internal.NewAnyValueBytesValue()
198 *m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
199 return ByteSlice(internal.NewByteSliceWrapper(&ov.BytesValue, m.getState()))
200 }
201
202 // PutEmptyMap inserts or updates an empty map under given key and returns it.
203 func (m Map) PutEmptyMap(k string) Map {
204 m.getState().AssertMutable()
205 if av, existing := m.Get(k); existing {
206 return av.SetEmptyMap()
207 }
208 ov := internal.NewAnyValueKvlistValue()
209 ov.KvlistValue = internal.NewKeyValueList()
210 *m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
211 return Map(internal.NewMapWrapper(&ov.KvlistValue.Values, m.getState()))
212 }
213
214 // PutEmptySlice inserts or updates an empty slice under given key and returns it.
215 func (m Map) PutEmptySlice(k string) Slice {
216 m.getState().AssertMutable()
217 if av, existing := m.Get(k); existing {
218 return av.SetEmptySlice()
219 }
220 ov := internal.NewAnyValueArrayValue()
221 ov.ArrayValue = internal.NewArrayValue()
222 *m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
223 return Slice(internal.NewSliceWrapper(&ov.ArrayValue.Values, m.getState()))
224 }
225
226 // Len returns the length of this map.
227 //
228 // Because the Map is represented internally by a slice of pointers, and the data are comping from the wire,
229 // it is possible that when iterating using "Range" to get access to fewer elements because nil elements are skipped.
230 func (m Map) Len() int {
231 return len(*m.getOrig())
232 }
233
234 // Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.
235 //
236 // Example:
237 //
238 // sm.Range(func(k string, v Value) bool {
239 // ...
240 // })
241 func (m Map) Range(f func(k string, v Value) bool) {
242 for i := range *m.getOrig() {
243 kv := &(*m.getOrig())[i]
244 if !f(kv.Key, Value(internal.NewValueWrapper(&kv.Value, m.getState()))) {
245 break
246 }
247 }
248 }
249
250 // All returns an iterator over key-value pairs in the Map.
251 //
252 // for k, v := range es.All() {
253 // ... // Do something with key-value pair
254 // }
255 func (m Map) All() iter.Seq2[string, Value] {
256 return func(yield func(string, Value) bool) {
257 for i := range *m.getOrig() {
258 kv := &(*m.getOrig())[i]
259 if !yield(kv.Key, Value(internal.NewValueWrapper(&kv.Value, m.getState()))) {
260 return
261 }
262 }
263 }
264 }
265
266 // MoveTo moves all key/values from the current map overriding the destination and
267 // resetting the current instance to its zero value
268 func (m Map) MoveTo(dest Map) {
269 m.getState().AssertMutable()
270 dest.getState().AssertMutable()
271 // If they point to the same data, they are the same, nothing to do.
272 if m.getOrig() == dest.getOrig() {
273 return
274 }
275 *dest.getOrig() = *m.getOrig()
276 *m.getOrig() = nil
277 }
278
279 // CopyTo copies all elements from the current map overriding the destination.
280 func (m Map) CopyTo(dest Map) {
281 dest.getState().AssertMutable()
282 if m.getOrig() == dest.getOrig() {
283 return
284 }
285 *dest.getOrig() = internal.CopyKeyValueSlice(*dest.getOrig(), *m.getOrig())
286 }
287
288 // AsRaw returns a standard go map representation of this Map.
289 func (m Map) AsRaw() map[string]any {
290 rawMap := make(map[string]any, m.Len())
291 m.Range(func(k string, v Value) bool {
292 rawMap[k] = v.AsRaw()
293 return true
294 })
295 return rawMap
296 }
297
298 // FromRaw overrides this Map instance from a standard go map.
299 func (m Map) FromRaw(rawMap map[string]any) error {
300 m.getState().AssertMutable()
301 if len(rawMap) == 0 {
302 *m.getOrig() = nil
303 return nil
304 }
305
306 var errs error
307 origs := make([]internal.KeyValue, len(rawMap))
308 ix := 0
309 for k, iv := range rawMap {
310 origs[ix].Key = k
311 errs = multierr.Append(errs, newValue(&origs[ix].Value, m.getState()).FromRaw(iv))
312 ix++
313 }
314 *m.getOrig() = origs
315 return errs
316 }
317
318 // Equal checks equality with another Map
319 func (m Map) Equal(val Map) bool {
320 if m.Len() != val.Len() {
321 return false
322 }
323
324 fullEqual := true
325
326 m.Range(func(k string, v Value) bool {
327 vv, ok := val.Get(k)
328 if !ok {
329 fullEqual = false
330 return fullEqual
331 }
332
333 if !v.Equal(vv) {
334 fullEqual = false
335 }
336 return fullEqual
337 })
338 return fullEqual
339 }