Debian Codegraph @

pdata/pcommon/value.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 "encoding/base64"
8 "encoding/json"
9 "fmt"
10 "math"
11 "strconv"
12
13 "go.opentelemetry.io/collector/pdata/internal"
14 )
15
16 // ValueType specifies the type of Value.
17 type ValueType int32
18
19 const (
20 ValueTypeEmpty ValueType = iota
21 ValueTypeStr
22 ValueTypeInt
23 ValueTypeDouble
24 ValueTypeBool
25 ValueTypeMap
26 ValueTypeSlice
27 ValueTypeBytes
28 )
29
30 // String returns the string representation of the ValueType.
31 func (avt ValueType) String() string {
32 switch avt {
33 case ValueTypeEmpty:
34 return "Empty"
35 case ValueTypeStr:
36 return "Str"
37 case ValueTypeBool:
38 return "Bool"
39 case ValueTypeInt:
40 return "Int"
41 case ValueTypeDouble:
42 return "Double"
43 case ValueTypeMap:
44 return "Map"
45 case ValueTypeSlice:
46 return "Slice"
47 case ValueTypeBytes:
48 return "Bytes"
49 }
50 return ""
51 }
52
53 // Value is a mutable cell containing any value. Typically used as an element of Map or Slice.
54 // Must use one of NewValue+ functions below to create new instances.
55 //
56 // Intended to be passed by value since internally it is just a pointer to actual
57 // value representation. For the same reason passing by value and calling setters
58 // will modify the original, e.g.:
59 //
60 // func f1(val Value) { val.SetInt(234) }
61 // func f2() {
62 // v := NewValueStr("a string")
63 // f1(v)
64 // _ := v.Type() // this will return ValueTypeInt
65 // }
66 //
67 // Important: zero-initialized instance is not valid for use. All Value functions below must
68 // be called only on instances that are created via NewValue+ functions.
69 type Value internal.ValueWrapper
70
71 // NewValueEmpty creates a new Value with an empty value.
72 func NewValueEmpty() Value {
73 return newValue(&internal.AnyValue{}, internal.NewState())
74 }
75
76 // NewValueStr creates a new Value with the given string value.
77 func NewValueStr(v string) Value {
78 ov := internal.NewAnyValueStringValue()
79 ov.StringValue = v
80 orig := internal.NewAnyValue()
81 orig.Value = ov
82 return newValue(orig, internal.NewState())
83 }
84
85 // NewValueInt creates a new Value with the given int64 value.
86 func NewValueInt(v int64) Value {
87 ov := internal.NewAnyValueIntValue()
88 ov.IntValue = v
89 orig := internal.NewAnyValue()
90 orig.Value = ov
91 return newValue(orig, internal.NewState())
92 }
93
94 // NewValueDouble creates a new Value with the given float64 value.
95 func NewValueDouble(v float64) Value {
96 ov := internal.NewAnyValueDoubleValue()
97 ov.DoubleValue = v
98 orig := internal.NewAnyValue()
99 orig.Value = ov
100 return newValue(orig, internal.NewState())
101 }
102
103 // NewValueBool creates a new Value with the given bool value.
104 func NewValueBool(v bool) Value {
105 ov := internal.NewAnyValueBoolValue()
106 ov.BoolValue = v
107 orig := internal.NewAnyValue()
108 orig.Value = ov
109 return newValue(orig, internal.NewState())
110 }
111
112 // NewValueMap creates a new Value of map type.
113 func NewValueMap() Value {
114 ov := internal.NewAnyValueKvlistValue()
115 ov.KvlistValue = internal.NewKeyValueList()
116 orig := internal.NewAnyValue()
117 orig.Value = ov
118 return newValue(orig, internal.NewState())
119 }
120
121 // NewValueSlice creates a new Value of array type.
122 func NewValueSlice() Value {
123 ov := internal.NewAnyValueArrayValue()
124 ov.ArrayValue = internal.NewArrayValue()
125 orig := internal.NewAnyValue()
126 orig.Value = ov
127 return newValue(orig, internal.NewState())
128 }
129
130 // NewValueBytes creates a new empty Value of byte type.
131 func NewValueBytes() Value {
132 ov := internal.NewAnyValueBytesValue()
133 orig := internal.NewAnyValue()
134 orig.Value = ov
135 return newValue(orig, internal.NewState())
136 }
137
138 func newValue(orig *internal.AnyValue, state *internal.State) Value {
139 return Value(internal.NewValueWrapper(orig, state))
140 }
141
142 func (v Value) getOrig() *internal.AnyValue {
143 return internal.GetValueOrig(internal.ValueWrapper(v))
144 }
145
146 func (v Value) getState() *internal.State {
147 return internal.GetValueState(internal.ValueWrapper(v))
148 }
149
150 // FromRaw sets the value from the given raw value.
151 // Calling this function on zero-initialized Value will cause a panic.
152 func (v Value) FromRaw(iv any) error {
153 switch tv := iv.(type) {
154 case nil:
155 v.getOrig().Value = nil
156 case string:
157 v.SetStr(tv)
158 case int:
159 v.SetInt(int64(tv))
160 case int8:
161 v.SetInt(int64(tv))
162 case int16:
163 v.SetInt(int64(tv))
164 case int32:
165 v.SetInt(int64(tv))
166 case int64:
167 v.SetInt(tv)
168 case uint:
169 v.SetInt(int64(tv))
170 case uint8:
171 v.SetInt(int64(tv))
172 case uint16:
173 v.SetInt(int64(tv))
174 case uint32:
175 v.SetInt(int64(tv))
176 case uint64:
177 v.SetInt(int64(tv))
178 case float32:
179 v.SetDouble(float64(tv))
180 case float64:
181 v.SetDouble(tv)
182 case bool:
183 v.SetBool(tv)
184 case []byte:
185 v.SetEmptyBytes().FromRaw(tv)
186 case map[string]any:
187 return v.SetEmptyMap().FromRaw(tv)
188 case []any:
189 return v.SetEmptySlice().FromRaw(tv)
190 default:
191 return fmt.Errorf("<Invalid value type %T>", tv)
192 }
193 return nil
194 }
195
196 // Type returns the type of the value for this Value.
197 // Calling this function on zero-initialized Value will cause a panic.
198 func (v Value) Type() ValueType {
199 switch v.getOrig().Value.(type) {
200 case *internal.AnyValue_StringValue:
201 return ValueTypeStr
202 case *internal.AnyValue_BoolValue:
203 return ValueTypeBool
204 case *internal.AnyValue_IntValue:
205 return ValueTypeInt
206 case *internal.AnyValue_DoubleValue:
207 return ValueTypeDouble
208 case *internal.AnyValue_KvlistValue:
209 return ValueTypeMap
210 case *internal.AnyValue_ArrayValue:
211 return ValueTypeSlice
212 case *internal.AnyValue_BytesValue:
213 return ValueTypeBytes
214 }
215 return ValueTypeEmpty
216 }
217
218 // Str returns the string value associated with this Value.
219 // The shorter name is used instead of String to avoid implementing fmt.Stringer interface.
220 // If the Type() is not ValueTypeStr then returns empty string.
221 func (v Value) Str() string {
222 return v.getOrig().GetStringValue()
223 }
224
225 // Int returns the int64 value associated with this Value.
226 // If the Type() is not ValueTypeInt then returns int64(0).
227 func (v Value) Int() int64 {
228 return v.getOrig().GetIntValue()
229 }
230
231 // Double returns the float64 value associated with this Value.
232 // If the Type() is not ValueTypeDouble then returns float64(0).
233 func (v Value) Double() float64 {
234 return v.getOrig().GetDoubleValue()
235 }
236
237 // Bool returns the bool value associated with this Value.
238 // If the Type() is not ValueTypeBool then returns false.
239 func (v Value) Bool() bool {
240 return v.getOrig().GetBoolValue()
241 }
242
243 // Map returns the map value associated with this Value.
244 // If the function is called on zero-initialized Value or if the Type() is not ValueTypeMap
245 // then it returns an invalid map. Note that using such map can cause panic.
246 func (v Value) Map() Map {
247 kvlist := v.getOrig().GetKvlistValue()
248 if kvlist == nil {
249 return Map{}
250 }
251 return newMap(&kvlist.Values, internal.GetValueState(internal.ValueWrapper(v)))
252 }
253
254 // Slice returns the slice value associated with this Value.
255 // If the function is called on zero-initialized Value or if the Type() is not ValueTypeSlice
256 // then returns an invalid slice. Note that using such slice can cause panic.
257 func (v Value) Slice() Slice {
258 arr := v.getOrig().GetArrayValue()
259 if arr == nil {
260 return Slice{}
261 }
262 return newSlice(&arr.Values, internal.GetValueState(internal.ValueWrapper(v)))
263 }
264
265 // Bytes returns the ByteSlice value associated with this Value.
266 // If the function is called on zero-initialized Value or if the Type() is not ValueTypeBytes
267 // then returns an invalid ByteSlice object. Note that using such slice can cause panic.
268 func (v Value) Bytes() ByteSlice {
269 bv, ok := v.getOrig().GetValue().(*internal.AnyValue_BytesValue)
270 if !ok {
271 return ByteSlice{}
272 }
273 return ByteSlice(internal.NewByteSliceWrapper(&bv.BytesValue, internal.GetValueState(internal.ValueWrapper(v))))
274 }
275
276 // SetStr replaces the string value associated with this Value,
277 // it also changes the type to be ValueTypeStr.
278 // The shorter name is used instead of SetString to avoid implementing
279 // fmt.Stringer interface by the corresponding getter method.
280 // Calling this function on zero-initialized Value will cause a panic.
281 func (v Value) SetStr(sv string) {
282 v.getState().AssertMutable()
283 // Delete everything but the AnyValue object itself.
284 internal.DeleteAnyValue(v.getOrig(), false)
285 ov := internal.NewAnyValueStringValue()
286 ov.StringValue = sv
287 v.getOrig().Value = ov
288 }
289
290 // SetInt replaces the int64 value associated with this Value,
291 // it also changes the type to be ValueTypeInt.
292 // Calling this function on zero-initialized Value will cause a panic.
293 func (v Value) SetInt(iv int64) {
294 v.getState().AssertMutable()
295 // Delete everything but the AnyValue object itself.
296 internal.DeleteAnyValue(v.getOrig(), false)
297 ov := internal.NewAnyValueIntValue()
298 ov.IntValue = iv
299 v.getOrig().Value = ov
300 }
301
302 // SetDouble replaces the float64 value associated with this Value,
303 // it also changes the type to be ValueTypeDouble.
304 // Calling this function on zero-initialized Value will cause a panic.
305 func (v Value) SetDouble(dv float64) {
306 v.getState().AssertMutable()
307 // Delete everything but the AnyValue object itself.
308 internal.DeleteAnyValue(v.getOrig(), false)
309 ov := internal.NewAnyValueDoubleValue()
310 ov.DoubleValue = dv
311 v.getOrig().Value = ov
312 }
313
314 // SetBool replaces the bool value associated with this Value,
315 // it also changes the type to be ValueTypeBool.
316 // Calling this function on zero-initialized Value will cause a panic.
317 func (v Value) SetBool(bv bool) {
318 v.getState().AssertMutable()
319 // Delete everything but the AnyValue object itself.
320 internal.DeleteAnyValue(v.getOrig(), false)
321 ov := internal.NewAnyValueBoolValue()
322 ov.BoolValue = bv
323 v.getOrig().Value = ov
324 }
325
326 // SetEmptyBytes sets value to an empty byte slice and returns it.
327 // Calling this function on zero-initialized Value will cause a panic.
328 func (v Value) SetEmptyBytes() ByteSlice {
329 v.getState().AssertMutable()
330 // Delete everything but the AnyValue object itself.
331 internal.DeleteAnyValue(v.getOrig(), false)
332 bv := internal.NewAnyValueBytesValue()
333 v.getOrig().Value = bv
334 return ByteSlice(internal.NewByteSliceWrapper(&bv.BytesValue, v.getState()))
335 }
336
337 // SetEmptyMap sets value to an empty map and returns it.
338 // Calling this function on zero-initialized Value will cause a panic.
339 func (v Value) SetEmptyMap() Map {
340 v.getState().AssertMutable()
341 // Delete everything but the AnyValue object itself.
342 internal.DeleteAnyValue(v.getOrig(), false)
343 ov := internal.NewAnyValueKvlistValue()
344 ov.KvlistValue = internal.NewKeyValueList()
345 v.getOrig().Value = ov
346 return newMap(&ov.KvlistValue.Values, v.getState())
347 }
348
349 // SetEmptySlice sets value to an empty slice and returns it.
350 // Calling this function on zero-initialized Value will cause a panic.
351 func (v Value) SetEmptySlice() Slice {
352 v.getState().AssertMutable()
353 // Delete everything but the AnyValue object itself.
354 internal.DeleteAnyValue(v.getOrig(), false)
355 ov := internal.NewAnyValueArrayValue()
356 ov.ArrayValue = internal.NewArrayValue()
357 v.getOrig().Value = ov
358 return newSlice(&ov.ArrayValue.Values, v.getState())
359 }
360
361 // MoveTo moves the Value from current overriding the destination and
362 // resetting the current instance to empty value.
363 // Calling this function on zero-initialized Value will cause a panic.
364 func (v Value) MoveTo(dest Value) {
365 v.getState().AssertMutable()
366 dest.getState().AssertMutable()
367 // If they point to the same data, they are the same, nothing to do.
368 if v.getOrig() == dest.getOrig() {
369 return
370 }
371 *dest.getOrig() = *v.getOrig()
372 v.getOrig().Value = nil
373 }
374
375 // CopyTo copies the Value instance overriding the destination.
376 // Calling this function on zero-initialized Value will cause a panic.
377 func (v Value) CopyTo(dest Value) {
378 dest.getState().AssertMutable()
379 internal.CopyAnyValue(dest.getOrig(), v.getOrig())
380 }
381
382 // AsString converts an OTLP Value object of any type to its equivalent string
383 // representation. This differs from Str which only returns a non-empty value
384 // if the ValueType is ValueTypeStr.
385 // Calling this function on zero-initialized Value will cause a panic.
386 func (v Value) AsString() string {
387 switch v.Type() {
388 case ValueTypeEmpty:
389 return ""
390
391 case ValueTypeStr:
392 return v.Str()
393
394 case ValueTypeBool:
395 return strconv.FormatBool(v.Bool())
396
397 case ValueTypeDouble:
398 return float64AsString(v.Double())
399
400 case ValueTypeInt:
401 return strconv.FormatInt(v.Int(), 10)
402
403 case ValueTypeMap:
404 jsonStr, _ := json.Marshal(v.Map().AsRaw())
405 return string(jsonStr)
406
407 case ValueTypeBytes:
408 return base64.StdEncoding.EncodeToString(*v.Bytes().getOrig())
409
410 case ValueTypeSlice:
411 jsonStr, _ := json.Marshal(v.Slice().AsRaw())
412 return string(jsonStr)
413
414 default:
415 return fmt.Sprintf("<Unknown OpenTelemetry attribute value type %q>", v.Type())
416 }
417 }
418
419 // See https://cs.opensource.google/go/go/+/refs/tags/go1.17.7:src/encoding/json/encode.go;l=585.
420 // This allows us to avoid using reflection.
421 func float64AsString(f float64) string {
422 if math.IsInf(f, 0) || math.IsNaN(f) {
423 return "json: unsupported value: " + strconv.FormatFloat(f, 'g', -1, 64)
424 }
425
426 // Convert as if by ES6 number to string conversion.
427 // This matches most other JSON generators.
428 // See golang.org/issue/6384 and golang.org/issue/14135.
429 // Like fmt %g, but the exponent cutoffs are different
430 // and exponents themselves are not padded to two digits.
431 scratch := [64]byte{}
432 b := scratch[:0]
433 abs := math.Abs(f)
434 fmt := byte('f')
435 if abs != 0 && (abs < 1e-6 || abs >= 1e21) {
436 fmt = 'e'
437 }
438 b = strconv.AppendFloat(b, f, fmt, -1, 64)
439 if fmt == 'e' {
440 // clean up e-09 to e-9
441 n := len(b)
442 if n >= 4 && b[n-4] == 'e' && b[n-3] == '-' && b[n-2] == '0' {
443 b[n-2] = b[n-1]
444 b = b[:n-1]
445 }
446 }
447 return string(b)
448 }
449
450 func (v Value) AsRaw() any {
451 switch v.Type() {
452 case ValueTypeEmpty:
453 return nil
454 case ValueTypeStr:
455 return v.Str()
456 case ValueTypeBool:
457 return v.Bool()
458 case ValueTypeDouble:
459 return v.Double()
460 case ValueTypeInt:
461 return v.Int()
462 case ValueTypeBytes:
463 return v.Bytes().AsRaw()
464 case ValueTypeMap:
465 return v.Map().AsRaw()
466 case ValueTypeSlice:
467 return v.Slice().AsRaw()
468 }
469 return fmt.Sprintf("<Unknown OpenTelemetry value type %q>", v.Type())
470 }
471
472 func (v Value) Equal(c Value) bool {
473 if v.Type() != c.Type() {
474 return false
475 }
476
477 switch v.Type() {
478 case ValueTypeEmpty:
479 return true
480 case ValueTypeStr:
481 return v.Str() == c.Str()
482 case ValueTypeBool:
483 return v.Bool() == c.Bool()
484 case ValueTypeDouble:
485 return v.Double() == c.Double()
486 case ValueTypeInt:
487 return v.Int() == c.Int()
488 case ValueTypeBytes:
489 return v.Bytes().Equal(c.Bytes())
490 case ValueTypeMap:
491 return v.Map().Equal(c.Map())
492 case ValueTypeSlice:
493 return v.Slice().Equal(c.Slice())
494 }
495
496 return false
497 }