Debian Codegraph @

pdata/internal/traceid.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package internal // import "go.opentelemetry.io/collector/pdata/internal"
5
6 import (
7 "encoding/hex"
8 "errors"
9
10 "go.opentelemetry.io/collector/pdata/internal/json"
11 )
12
13 const traceIDSize = 16
14
15 var errUnmarshalTraceID = errors.New("unmarshal: invalid TraceID length")
16
17 // TraceID is a custom data type that is used for all trace_id fields in OTLP
18 // Protobuf messages.
19 type TraceID [traceIDSize]byte
20
21 func DeleteTraceID(*TraceID, bool) {}
22
23 func CopyTraceID(dest, src *TraceID) {
24 *dest = *src
25 }
26
27 // IsEmpty returns true if id contains at leas one non-zero byte.
28 func (tid TraceID) IsEmpty() bool {
29 return tid == [traceIDSize]byte{}
30 }
31
32 // SizeProto returns the size of the data to serialize in proto format.
33 func (tid TraceID) SizeProto() int {
34 if tid.IsEmpty() {
35 return 0
36 }
37
38 return traceIDSize
39 }
40
41 // MarshalProto converts trace ID into a binary representation. Called by Protobuf serialization.
42 func (tid TraceID) MarshalProto(buf []byte) int {
43 if tid.IsEmpty() {
44 return 0
45 }
46
47 return copy(buf[len(buf)-traceIDSize:], tid[:])
48 }
49
50 // UnmarshalProto inflates this trace ID from binary representation. Called by Protobuf serialization.
51 func (tid *TraceID) UnmarshalProto(buf []byte) error {
52 if len(buf) == 0 {
53 *tid = [traceIDSize]byte{}
54 return nil
55 }
56
57 if len(buf) != traceIDSize {
58 return errUnmarshalTraceID
59 }
60
61 copy(tid[:], buf)
62 return nil
63 }
64
65 // MarshalJSON converts TraceID into a hex string.
66 //
67 //nolint:govet
68 func (tid TraceID) MarshalJSON(dest *json.Stream) {
69 dest.WriteString(hex.EncodeToString(tid[:]))
70 }
71
72 // UnmarshalJSON decodes TraceID from hex string.
73 //
74 //nolint:govet
75 func (tid *TraceID) UnmarshalJSON(iter *json.Iterator) {
76 *tid = [profileIDSize]byte{}
77 unmarshalJSON(tid[:], iter)
78 }
79
80 func GenTestTraceID() *TraceID {
81 tid := TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})
82 return &tid
83 }