Debian Codegraph @

attribute/internal/attribute.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 /*
5 Package attribute provide several helper functions for some commonly used
6 logic of processing attributes.
7 */
8 package attribute // import "go.opentelemetry.io/otel/attribute/internal"
9
10 import (
11 "reflect"
12 )
13
14 // sliceElem is the exact set of element types stored in attribute slice values.
15 // Using a closed set prevents accidental instantiations for unsupported types.
16 type sliceElem interface {
17 bool | int64 | float64 | string
18 }
19
20 // SliceValue converts a slice into an array with the same elements.
21 func SliceValue[T sliceElem](v []T) any {
22 // Keep only the common tiny-slice cases out of reflection. Extending this
23 // much further increases code size for diminishing benefit while larger
24 // slices still need the generic reflective path to preserve comparability.
25 // This matches the short lengths that show up most often in local
26 // benchmarks and semantic convention examples while leaving larger, less
27 // predictable slices on the generic reflective path.
28 switch len(v) {
29 case 0:
30 return [0]T{}
31 case 1:
32 return [1]T{v[0]}
33 case 2:
34 return [2]T{v[0], v[1]}
35 case 3:
36 return [3]T{v[0], v[1], v[2]}
37 }
38
39 return sliceValueReflect(v)
40 }
41
42 // AsSlice converts an array into a slice with the same elements.
43 func AsSlice[T sliceElem](v any) []T {
44 // Mirror the small fixed-array fast path used by SliceValue.
45 switch a := v.(type) {
46 case [0]T:
47 return []T{}
48 case [1]T:
49 return []T{a[0]}
50 case [2]T:
51 return []T{a[0], a[1]}
52 case [3]T:
53 return []T{a[0], a[1], a[2]}
54 }
55
56 return asSliceReflect[T](v)
57 }
58
59 func sliceValueReflect[T sliceElem](v []T) any {
60 cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeFor[T]())).Elem()
61 reflect.Copy(cp, reflect.ValueOf(v))
62 return cp.Interface()
63 }
64
65 func asSliceReflect[T sliceElem](v any) []T {
66 rv := reflect.ValueOf(v)
67 if !rv.IsValid() || rv.Kind() != reflect.Array || rv.Type().Elem() != reflect.TypeFor[T]() {
68 return nil
69 }
70 cpy := make([]T, rv.Len())
71 if len(cpy) > 0 {
72 _ = reflect.Copy(reflect.ValueOf(cpy), rv)
73 }
74 return cpy
75 }