| 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 spanIDSize = 8 |
| 14 |
|
| 15 |
var errUnmarshalSpanID = errors.New("unmarshal: invalid SpanID length") |
| 16 |
|
| 17 |
// SpanID is a custom data type that is used for all span_id fields in OTLP |
| 18 |
// Protobuf messages. |
| 19 |
type SpanID [spanIDSize]byte |
| 20 |
|
| 21 |
func DeleteSpanID(*SpanID, bool) {} |
| 22 |
|
| 23 |
func CopySpanID(dest, src *SpanID) { |
| 24 |
*dest = *src |
| 25 |
} |
| 26 |
|
| 27 |
// IsEmpty returns true if id contains at least one non-zero byte. |
| 28 |
func (sid SpanID) IsEmpty() bool { |
| 29 |
return sid == [spanIDSize]byte{} |
| 30 |
} |
| 31 |
|
| 32 |
// SizeProto returns the size of the data to serialize in proto format. |
| 33 |
func (sid SpanID) SizeProto() int { |
| 34 |
if sid.IsEmpty() { |
| 35 |
return 0 |
| 36 |
} |
| 37 |
return spanIDSize |
| 38 |
} |
| 39 |
|
| 40 |
// MarshalProto converts span ID into a binary representation. Called by Protobuf serialization. |
| 41 |
func (sid SpanID) MarshalProto(buf []byte) int { |
| 42 |
if sid.IsEmpty() { |
| 43 |
return 0 |
| 44 |
} |
| 45 |
|
| 46 |
return copy(buf[len(buf)-spanIDSize:], sid[:]) |
| 47 |
} |
| 48 |
|
| 49 |
// UnmarshalProto inflates this span ID from binary representation. Called by Protobuf serialization. |
| 50 |
func (sid *SpanID) UnmarshalProto(data []byte) error { |
| 51 |
if len(data) == 0 { |
| 52 |
*sid = [spanIDSize]byte{} |
| 53 |
return nil |
| 54 |
} |
| 55 |
|
| 56 |
if len(data) != spanIDSize { |
| 57 |
return errUnmarshalSpanID |
| 58 |
} |
| 59 |
|
| 60 |
copy(sid[:], data) |
| 61 |
return nil |
| 62 |
} |
| 63 |
|
| 64 |
// MarshalJSON converts SpanID into a hex string. |
| 65 |
// |
| 66 |
//nolint:govet |
| 67 |
func (sid SpanID) MarshalJSON(dest *json.Stream) { |
| 68 |
dest.WriteString(hex.EncodeToString(sid[:])) |
| 69 |
} |
| 70 |
|
| 71 |
// UnmarshalJSON decodes SpanID from hex string. |
| 72 |
// |
| 73 |
//nolint:govet |
| 74 |
func (sid *SpanID) UnmarshalJSON(iter *json.Iterator) { |
| 75 |
*sid = [spanIDSize]byte{} |
| 76 |
unmarshalJSON(sid[:], iter) |
| 77 |
} |
| 78 |
|
| 79 |
func GenTestSpanID() *SpanID { |
| 80 |
sid := SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1}) |
| 81 |
return &sid |
| 82 |
} |