Debian Codegraph @

sdk/metric/exemplar/value.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package exemplar // import "go.opentelemetry.io/otel/sdk/metric/exemplar"
5
6 import "math"
7
8 // ValueType identifies the type of value used in exemplar data.
9 type ValueType uint8
10
11 const (
12 // UnknownValueType should not be used. It represents a misconfigured
13 // Value.
14 UnknownValueType ValueType = 0
15 // Int64ValueType represents a Value with int64 data.
16 Int64ValueType ValueType = 1
17 // Float64ValueType represents a Value with float64 data.
18 Float64ValueType ValueType = 2
19 )
20
21 // Value is the value of data held by an exemplar.
22 type Value struct {
23 t ValueType
24 val uint64
25 }
26
27 // NewValue returns a new [Value] for the provided value.
28 func NewValue[N int64 | float64](value N) Value {
29 switch v := any(value).(type) {
30 case int64:
31 // This can be later converted back to int64 (overflow not checked).
32 return Value{t: Int64ValueType, val: uint64(v)} // nolint:gosec
33 case float64:
34 return Value{t: Float64ValueType, val: math.Float64bits(v)}
35 }
36 return Value{}
37 }
38
39 // Type returns the [ValueType] of data held by v.
40 func (v Value) Type() ValueType { return v.t }
41
42 // Int64 returns the value of v as an int64. If the ValueType of v is not an
43 // Int64ValueType, 0 is returned.
44 func (v Value) Int64() int64 {
45 if v.t == Int64ValueType {
46 // Assumes the correct int64 was stored in v.val based on type.
47 return int64(v.val) // nolint: gosec
48 }
49 return 0
50 }
51
52 // Float64 returns the value of v as an float64. If the ValueType of v is not
53 // an Float64ValueType, 0 is returned.
54 func (v Value) Float64() float64 {
55 if v.t == Float64ValueType {
56 return math.Float64frombits(v.val)
57 }
58 return 0
59 }