// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
import (
"encoding/hex"
"go.opentelemetry.io/collector/pdata/internal/json"
)
// unmarshalJSON inflates trace id from hex string, possibly enclosed in quotes.
// Called by Protobuf JSON deserialization.
func unmarshalJSON(dst []byte, iter *json.Iterator) {
src := iter.ReadStringAsSlice()
if len(src) == 0 {
return
}
if len(dst) != hex.DecodedLen(len(src)) {
iter.ReportError("ID.UnmarshalJSONIter", "length mismatch")
return
}
_, err := hex.Decode(dst, src)
if err != nil {
iter.ReportError("ID.UnmarshalJSONIter", err.Error())
return
}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"math"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
func (m *AnyValue) GetValue() any {
if m != nil {
return m.Value
}
return nil
}
func (m *AnyValue) deleteValue() {
if m == nil {
return
}
switch ov := m.Value.(type) {
case *AnyValue_StringValue:
deleteAnyValue_StringValue(ov)
case *AnyValue_BoolValue:
deleteAnyValue_BoolValue(ov)
case *AnyValue_IntValue:
deleteAnyValue_IntValue(ov)
case *AnyValue_DoubleValue:
deleteAnyValue_DoubleValue(ov)
case *AnyValue_ArrayValue:
deleteAnyValue_ArrayValue(ov)
case *AnyValue_KvlistValue:
deleteAnyValue_KvlistValue(ov)
case *AnyValue_BytesValue:
deleteAnyValue_BytesValue(ov)
case *AnyValue_StringValueStrindex:
deleteAnyValue_StringValueStrindex(ov)
}
m.Value = nil
}
var (
protoPoolAnyValue_StringValue = sync.Pool{
New: func() any {
return &AnyValue_StringValue{}
},
}
)
type AnyValue_StringValue struct {
StringValue string
}
func NewAnyValue_StringValue() *AnyValue_StringValue {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &AnyValue_StringValue{}
}
return protoPoolAnyValue_StringValue.Get().(*AnyValue_StringValue)
}
func deleteAnyValue_StringValue(v *AnyValue_StringValue) {
// Called only when pool is enabled
v.StringValue = ""
protoPoolAnyValue_StringValue.Put(v)
}
func (m *AnyValue) GetStringValue() string {
if v, ok := m.GetValue().(*AnyValue_StringValue); ok {
return v.StringValue
}
return ""
}
func (m *AnyValue) SetStringValue(val string) {
if m.Value != nil {
// Reuse message if possible, otherwise delete and create a new one.
if v, ok := m.GetValue().(*AnyValue_StringValue); ok {
v.StringValue = val
return
}
m.deleteValue()
}
v := NewAnyValue_StringValue()
v.StringValue = val
m.Value = v
}
var (
protoPoolAnyValue_BoolValue = sync.Pool{
New: func() any {
return &AnyValue_BoolValue{}
},
}
)
type AnyValue_BoolValue struct {
BoolValue bool
}
func NewAnyValue_BoolValue() *AnyValue_BoolValue {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &AnyValue_BoolValue{}
}
return protoPoolAnyValue_BoolValue.Get().(*AnyValue_BoolValue)
}
func deleteAnyValue_BoolValue(v *AnyValue_BoolValue) {
// Called only when pool is enabled
v.BoolValue = false
protoPoolAnyValue_BoolValue.Put(v)
}
func (m *AnyValue) GetBoolValue() bool {
if v, ok := m.GetValue().(*AnyValue_BoolValue); ok {
return v.BoolValue
}
return false
}
func (m *AnyValue) SetBoolValue(val bool) {
if m.Value != nil {
// Reuse message if possible, otherwise delete and create a new one.
if v, ok := m.GetValue().(*AnyValue_BoolValue); ok {
v.BoolValue = val
return
}
m.deleteValue()
}
v := NewAnyValue_BoolValue()
v.BoolValue = val
m.Value = v
}
var (
protoPoolAnyValue_IntValue = sync.Pool{
New: func() any {
return &AnyValue_IntValue{}
},
}
)
type AnyValue_IntValue struct {
IntValue int64
}
func NewAnyValue_IntValue() *AnyValue_IntValue {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &AnyValue_IntValue{}
}
return protoPoolAnyValue_IntValue.Get().(*AnyValue_IntValue)
}
func deleteAnyValue_IntValue(v *AnyValue_IntValue) {
// Called only when pool is enabled
v.IntValue = int64(0)
protoPoolAnyValue_IntValue.Put(v)
}
func (m *AnyValue) GetIntValue() int64 {
if v, ok := m.GetValue().(*AnyValue_IntValue); ok {
return v.IntValue
}
return int64(0)
}
func (m *AnyValue) SetIntValue(val int64) {
if m.Value != nil {
// Reuse message if possible, otherwise delete and create a new one.
if v, ok := m.GetValue().(*AnyValue_IntValue); ok {
v.IntValue = val
return
}
m.deleteValue()
}
v := NewAnyValue_IntValue()
v.IntValue = val
m.Value = v
}
var (
protoPoolAnyValue_DoubleValue = sync.Pool{
New: func() any {
return &AnyValue_DoubleValue{}
},
}
)
type AnyValue_DoubleValue struct {
DoubleValue float64
}
func NewAnyValue_DoubleValue() *AnyValue_DoubleValue {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &AnyValue_DoubleValue{}
}
return protoPoolAnyValue_DoubleValue.Get().(*AnyValue_DoubleValue)
}
func deleteAnyValue_DoubleValue(v *AnyValue_DoubleValue) {
// Called only when pool is enabled
v.DoubleValue = float64(0)
protoPoolAnyValue_DoubleValue.Put(v)
}
func (m *AnyValue) GetDoubleValue() float64 {
if v, ok := m.GetValue().(*AnyValue_DoubleValue); ok {
return v.DoubleValue
}
return float64(0)
}
func (m *AnyValue) SetDoubleValue(val float64) {
if m.Value != nil {
// Reuse message if possible, otherwise delete and create a new one.
if v, ok := m.GetValue().(*AnyValue_DoubleValue); ok {
v.DoubleValue = val
return
}
m.deleteValue()
}
v := NewAnyValue_DoubleValue()
v.DoubleValue = val
m.Value = v
}
var (
protoPoolAnyValue_ArrayValue = sync.Pool{
New: func() any {
return &AnyValue_ArrayValue{}
},
}
)
type AnyValue_ArrayValue struct {
ArrayValue *ArrayValue
}
func NewAnyValue_ArrayValue() *AnyValue_ArrayValue {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &AnyValue_ArrayValue{}
}
return protoPoolAnyValue_ArrayValue.Get().(*AnyValue_ArrayValue)
}
func deleteAnyValue_ArrayValue(v *AnyValue_ArrayValue) {
// Called only when pool is enabled
v.ArrayValue = nil
protoPoolAnyValue_ArrayValue.Put(v)
}
func (m *AnyValue) GetArrayValue() *ArrayValue {
if v, ok := m.GetValue().(*AnyValue_ArrayValue); ok {
return v.ArrayValue
}
return nil
}
var (
protoPoolAnyValue_KvlistValue = sync.Pool{
New: func() any {
return &AnyValue_KvlistValue{}
},
}
)
type AnyValue_KvlistValue struct {
KvlistValue *KeyValueList
}
func NewAnyValue_KvlistValue() *AnyValue_KvlistValue {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &AnyValue_KvlistValue{}
}
return protoPoolAnyValue_KvlistValue.Get().(*AnyValue_KvlistValue)
}
func deleteAnyValue_KvlistValue(v *AnyValue_KvlistValue) {
// Called only when pool is enabled
v.KvlistValue = nil
protoPoolAnyValue_KvlistValue.Put(v)
}
func (m *AnyValue) GetKvlistValue() *KeyValueList {
if v, ok := m.GetValue().(*AnyValue_KvlistValue); ok {
return v.KvlistValue
}
return nil
}
var (
protoPoolAnyValue_BytesValue = sync.Pool{
New: func() any {
return &AnyValue_BytesValue{}
},
}
)
type AnyValue_BytesValue struct {
BytesValue []byte
}
func NewAnyValue_BytesValue() *AnyValue_BytesValue {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &AnyValue_BytesValue{}
}
return protoPoolAnyValue_BytesValue.Get().(*AnyValue_BytesValue)
}
func deleteAnyValue_BytesValue(v *AnyValue_BytesValue) {
// Called only when pool is enabled
v.BytesValue = nil
protoPoolAnyValue_BytesValue.Put(v)
}
func (m *AnyValue) GetBytesValue() []byte {
if v, ok := m.GetValue().(*AnyValue_BytesValue); ok {
return v.BytesValue
}
return nil
}
func (m *AnyValue) SetBytesValue(val []byte) {
if m.Value != nil {
// Reuse message if possible, otherwise delete and create a new one.
if v, ok := m.GetValue().(*AnyValue_BytesValue); ok {
v.BytesValue = val
return
}
m.deleteValue()
}
v := NewAnyValue_BytesValue()
v.BytesValue = val
m.Value = v
}
var (
protoPoolAnyValue_StringValueStrindex = sync.Pool{
New: func() any {
return &AnyValue_StringValueStrindex{}
},
}
)
type AnyValue_StringValueStrindex struct {
StringValueStrindex int32
}
func NewAnyValue_StringValueStrindex() *AnyValue_StringValueStrindex {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &AnyValue_StringValueStrindex{}
}
return protoPoolAnyValue_StringValueStrindex.Get().(*AnyValue_StringValueStrindex)
}
func deleteAnyValue_StringValueStrindex(v *AnyValue_StringValueStrindex) {
// Called only when pool is enabled
v.StringValueStrindex = int32(0)
protoPoolAnyValue_StringValueStrindex.Put(v)
}
func (m *AnyValue) GetStringValueStrindex() int32 {
if v, ok := m.GetValue().(*AnyValue_StringValueStrindex); ok {
return v.StringValueStrindex
}
return int32(0)
}
func (m *AnyValue) SetStringValueStrindex(val int32) {
if m.Value != nil {
// Reuse message if possible, otherwise delete and create a new one.
if v, ok := m.GetValue().(*AnyValue_StringValueStrindex); ok {
v.StringValueStrindex = val
return
}
m.deleteValue()
}
v := NewAnyValue_StringValueStrindex()
v.StringValueStrindex = val
m.Value = v
}
type AnyValue struct {
Value any
}
var (
protoPoolAnyValue = sync.Pool{
New: func() any {
return &AnyValue{}
},
}
)
func NewAnyValue() *AnyValue {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &AnyValue{}
}
return protoPoolAnyValue.Get().(*AnyValue)
}
func DeleteAnyValue(orig *AnyValue, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.deleteValue()
orig.Reset()
if nullable {
protoPoolAnyValue.Put(orig)
}
}
func CopyAnyValue(dest, src *AnyValue) *AnyValue {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewAnyValue()
}
switch t := src.Value.(type) {
case *AnyValue_StringValue:
ov := NewAnyValue_StringValue()
ov.StringValue = t.StringValue
dest.Value = ov
case *AnyValue_BoolValue:
ov := NewAnyValue_BoolValue()
ov.BoolValue = t.BoolValue
dest.Value = ov
case *AnyValue_IntValue:
ov := NewAnyValue_IntValue()
ov.IntValue = t.IntValue
dest.Value = ov
case *AnyValue_DoubleValue:
ov := NewAnyValue_DoubleValue()
ov.DoubleValue = t.DoubleValue
dest.Value = ov
case *AnyValue_ArrayValue:
ov := NewAnyValue_ArrayValue()
ov.ArrayValue = NewArrayValue()
CopyArrayValue(ov.ArrayValue, t.ArrayValue)
dest.Value = ov
case *AnyValue_KvlistValue:
ov := NewAnyValue_KvlistValue()
ov.KvlistValue = NewKeyValueList()
CopyKeyValueList(ov.KvlistValue, t.KvlistValue)
dest.Value = ov
case *AnyValue_BytesValue:
ov := NewAnyValue_BytesValue()
ov.BytesValue = append(ov.BytesValue[:0], t.BytesValue...)
dest.Value = ov
case *AnyValue_StringValueStrindex:
ov := NewAnyValue_StringValueStrindex()
ov.StringValueStrindex = t.StringValueStrindex
dest.Value = ov
default:
dest.Value = nil
}
return dest
}
func CopyAnyValueSlice(dest, src []AnyValue) []AnyValue {
var newDest []AnyValue
if cap(dest) < len(src) {
newDest = make([]AnyValue, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteAnyValue(&dest[i], false)
}
}
for i := range src {
CopyAnyValue(&newDest[i], &src[i])
}
return newDest
}
func CopyAnyValuePtrSlice(dest, src []*AnyValue) []*AnyValue {
var newDest []*AnyValue
if cap(dest) < len(src) {
newDest = make([]*AnyValue, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewAnyValue()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteAnyValue(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewAnyValue()
}
}
for i := range src {
CopyAnyValue(newDest[i], src[i])
}
return newDest
}
func (orig *AnyValue) Reset() {
*orig = AnyValue{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *AnyValue) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
switch orig := orig.Value.(type) {
case *AnyValue_StringValue:
dest.WriteObjectField("stringValue")
dest.WriteString(orig.StringValue)
case *AnyValue_BoolValue:
dest.WriteObjectField("boolValue")
dest.WriteBool(orig.BoolValue)
case *AnyValue_IntValue:
dest.WriteObjectField("intValue")
dest.WriteInt64(orig.IntValue)
case *AnyValue_DoubleValue:
dest.WriteObjectField("doubleValue")
dest.WriteFloat64(orig.DoubleValue)
case *AnyValue_ArrayValue:
if orig.ArrayValue != nil {
dest.WriteObjectField("arrayValue")
orig.ArrayValue.MarshalJSON(dest)
}
case *AnyValue_KvlistValue:
if orig.KvlistValue != nil {
dest.WriteObjectField("kvlistValue")
orig.KvlistValue.MarshalJSON(dest)
}
case *AnyValue_BytesValue:
dest.WriteObjectField("bytesValue")
dest.WriteBytes(orig.BytesValue)
case *AnyValue_StringValueStrindex:
dest.WriteObjectField("stringValueStrindex")
dest.WriteInt32(orig.StringValueStrindex)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *AnyValue) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "stringValue", "string_value":
{
ov := NewAnyValue_StringValue()
ov.StringValue = iter.ReadString()
orig.Value = ov
}
case "boolValue", "bool_value":
{
ov := NewAnyValue_BoolValue()
ov.BoolValue = iter.ReadBool()
orig.Value = ov
}
case "intValue", "int_value":
{
ov := NewAnyValue_IntValue()
ov.IntValue = iter.ReadInt64()
orig.Value = ov
}
case "doubleValue", "double_value":
{
ov := NewAnyValue_DoubleValue()
ov.DoubleValue = iter.ReadFloat64()
orig.Value = ov
}
case "arrayValue", "array_value":
{
ov := NewAnyValue_ArrayValue()
ov.ArrayValue = NewArrayValue()
ov.ArrayValue.UnmarshalJSON(iter)
orig.Value = ov
}
case "kvlistValue", "kvlist_value":
{
ov := NewAnyValue_KvlistValue()
ov.KvlistValue = NewKeyValueList()
ov.KvlistValue.UnmarshalJSON(iter)
orig.Value = ov
}
case "bytesValue", "bytes_value":
{
ov := NewAnyValue_BytesValue()
ov.BytesValue = iter.ReadBytes()
orig.Value = ov
}
case "stringValueStrindex", "string_value_strindex":
{
ov := NewAnyValue_StringValueStrindex()
ov.StringValueStrindex = iter.ReadInt32()
orig.Value = ov
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *AnyValue) SizeProto() int {
var n int
var l int
_ = l
switch orig := orig.Value.(type) {
case nil:
_ = orig
break
case *AnyValue_StringValue:
l = len(orig.StringValue)
n += 1 + proto.Sov(uint64(l)) + l
case *AnyValue_BoolValue:
n += 2
case *AnyValue_IntValue:
n += 1 + proto.Sov(uint64(orig.IntValue))
case *AnyValue_DoubleValue:
n += 9
case *AnyValue_ArrayValue:
if orig.ArrayValue != nil {
l = orig.ArrayValue.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
case *AnyValue_KvlistValue:
if orig.KvlistValue != nil {
l = orig.KvlistValue.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
case *AnyValue_BytesValue:
l = len(orig.BytesValue)
n += 1 + proto.Sov(uint64(l)) + l
case *AnyValue_StringValueStrindex:
n += 1 + proto.Sov(uint64(orig.StringValueStrindex))
}
return n
}
func (orig *AnyValue) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
switch orig := orig.Value.(type) {
case *AnyValue_StringValue:
l = len(orig.StringValue)
pos -= l
copy(buf[pos:], orig.StringValue)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
case *AnyValue_BoolValue:
pos--
if orig.BoolValue {
buf[pos] = 1
} else {
buf[pos] = 0
}
pos--
buf[pos] = 0x10
case *AnyValue_IntValue:
pos = proto.EncodeVarint(buf, pos, uint64(orig.IntValue))
pos--
buf[pos] = 0x18
case *AnyValue_DoubleValue:
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.DoubleValue))
pos--
buf[pos] = 0x21
case *AnyValue_ArrayValue:
if orig.ArrayValue != nil {
l = orig.ArrayValue.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x2a
}
case *AnyValue_KvlistValue:
if orig.KvlistValue != nil {
l = orig.KvlistValue.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x32
}
case *AnyValue_BytesValue:
l = len(orig.BytesValue)
pos -= l
copy(buf[pos:], orig.BytesValue)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x3a
case *AnyValue_StringValueStrindex:
pos = proto.EncodeVarint(buf, pos, uint64(orig.StringValueStrindex))
pos--
buf[pos] = 0x40
}
return len(buf) - pos
}
func (orig *AnyValue) UnmarshalProto(buf []byte) error {
return orig.unmarshalProto(buf, 0)
}
func (orig *AnyValue) unmarshalProto(buf []byte, depth int) error {
if depth >= proto.RecursionLimit {
return proto.ErrRecursionDepth
}
depth++
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field StringValue", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewAnyValue_StringValue()
ov.StringValue = string(buf[startPos:pos])
orig.Value = ov
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field BoolValue", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
ov := NewAnyValue_BoolValue()
ov.BoolValue = num != 0
orig.Value = ov
case 3:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field IntValue", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
ov := NewAnyValue_IntValue()
ov.IntValue = int64(num)
orig.Value = ov
case 4:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field DoubleValue", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
ov := NewAnyValue_DoubleValue()
ov.DoubleValue = math.Float64frombits(num)
orig.Value = ov
case 5:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ArrayValue", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewAnyValue_ArrayValue()
ov.ArrayValue = NewArrayValue()
err = ov.ArrayValue.unmarshalProto(buf[startPos:pos], depth)
if err != nil {
return err
}
orig.Value = ov
case 6:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field KvlistValue", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewAnyValue_KvlistValue()
ov.KvlistValue = NewKeyValueList()
err = ov.KvlistValue.unmarshalProto(buf[startPos:pos], depth)
if err != nil {
return err
}
orig.Value = ov
case 7:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field BytesValue", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewAnyValue_BytesValue()
if length != 0 {
ov.BytesValue = make([]byte, length)
copy(ov.BytesValue, buf[startPos:pos])
}
orig.Value = ov
case 8:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field StringValueStrindex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
ov := NewAnyValue_StringValueStrindex()
ov.StringValueStrindex = int32(num)
orig.Value = ov
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestAnyValue() *AnyValue {
orig := NewAnyValue()
orig.Value = &AnyValue_StringValue{StringValue: "test_stringvalue"}
return orig
}
func GenTestAnyValuePtrSlice() []*AnyValue {
orig := make([]*AnyValue, 5)
orig[0] = NewAnyValue()
orig[1] = GenTestAnyValue()
orig[2] = NewAnyValue()
orig[3] = GenTestAnyValue()
orig[4] = NewAnyValue()
return orig
}
func GenTestAnyValueSlice() []AnyValue {
orig := make([]AnyValue, 5)
orig[1] = *GenTestAnyValue()
orig[3] = *GenTestAnyValue()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ArrayValue is a list of AnyValue messages. We need ArrayValue as a message since oneof in AnyValue does not allow repeated fields.
type ArrayValue struct {
Values []AnyValue
}
var (
protoPoolArrayValue = sync.Pool{
New: func() any {
return &ArrayValue{}
},
}
)
func NewArrayValue() *ArrayValue {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ArrayValue{}
}
return protoPoolArrayValue.Get().(*ArrayValue)
}
func DeleteArrayValue(orig *ArrayValue, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.Values {
DeleteAnyValue(&orig.Values[i], false)
}
orig.Reset()
if nullable {
protoPoolArrayValue.Put(orig)
}
}
func CopyArrayValue(dest, src *ArrayValue) *ArrayValue {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewArrayValue()
}
dest.Values = CopyAnyValueSlice(dest.Values, src.Values)
return dest
}
func CopyArrayValueSlice(dest, src []ArrayValue) []ArrayValue {
var newDest []ArrayValue
if cap(dest) < len(src) {
newDest = make([]ArrayValue, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteArrayValue(&dest[i], false)
}
}
for i := range src {
CopyArrayValue(&newDest[i], &src[i])
}
return newDest
}
func CopyArrayValuePtrSlice(dest, src []*ArrayValue) []*ArrayValue {
var newDest []*ArrayValue
if cap(dest) < len(src) {
newDest = make([]*ArrayValue, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewArrayValue()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteArrayValue(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewArrayValue()
}
}
for i := range src {
CopyArrayValue(newDest[i], src[i])
}
return newDest
}
func (orig *ArrayValue) Reset() {
*orig = ArrayValue{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ArrayValue) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.Values) > 0 {
dest.WriteObjectField("values")
dest.WriteArrayStart()
orig.Values[0].MarshalJSON(dest)
for i := 1; i < len(orig.Values); i++ {
dest.WriteMore()
orig.Values[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ArrayValue) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "values":
for iter.ReadArray() {
orig.Values = append(orig.Values, AnyValue{})
orig.Values[len(orig.Values)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ArrayValue) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.Values {
l = orig.Values[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ArrayValue) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.Values) - 1; i >= 0; i-- {
l = orig.Values[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *ArrayValue) UnmarshalProto(buf []byte) error {
return orig.unmarshalProto(buf, 0)
}
func (orig *ArrayValue) unmarshalProto(buf []byte, depth int) error {
if depth >= proto.RecursionLimit {
return proto.ErrRecursionDepth
}
depth++
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Values", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Values = append(orig.Values, AnyValue{})
err = orig.Values[len(orig.Values)-1].unmarshalProto(buf[startPos:pos], depth)
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestArrayValue() *ArrayValue {
orig := NewArrayValue()
orig.Values = []AnyValue{{}, *GenTestAnyValue()}
return orig
}
func GenTestArrayValuePtrSlice() []*ArrayValue {
orig := make([]*ArrayValue, 5)
orig[0] = NewArrayValue()
orig[1] = GenTestArrayValue()
orig[2] = NewArrayValue()
orig[3] = GenTestArrayValue()
orig[4] = NewArrayValue()
return orig
}
func GenTestArrayValueSlice() []ArrayValue {
orig := make([]ArrayValue, 5)
orig[1] = *GenTestArrayValue()
orig[3] = *GenTestArrayValue()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type EntityRef struct {
SchemaUrl string
Type string
IdKeys []string
DescriptionKeys []string
}
var (
protoPoolEntityRef = sync.Pool{
New: func() any {
return &EntityRef{}
},
}
)
func NewEntityRef() *EntityRef {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &EntityRef{}
}
return protoPoolEntityRef.Get().(*EntityRef)
}
func DeleteEntityRef(orig *EntityRef, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolEntityRef.Put(orig)
}
}
func CopyEntityRef(dest, src *EntityRef) *EntityRef {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewEntityRef()
}
dest.SchemaUrl = src.SchemaUrl
dest.Type = src.Type
dest.IdKeys = append(dest.IdKeys[:0], src.IdKeys...)
dest.DescriptionKeys = append(dest.DescriptionKeys[:0], src.DescriptionKeys...)
return dest
}
func CopyEntityRefSlice(dest, src []EntityRef) []EntityRef {
var newDest []EntityRef
if cap(dest) < len(src) {
newDest = make([]EntityRef, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteEntityRef(&dest[i], false)
}
}
for i := range src {
CopyEntityRef(&newDest[i], &src[i])
}
return newDest
}
func CopyEntityRefPtrSlice(dest, src []*EntityRef) []*EntityRef {
var newDest []*EntityRef
if cap(dest) < len(src) {
newDest = make([]*EntityRef, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewEntityRef()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteEntityRef(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewEntityRef()
}
}
for i := range src {
CopyEntityRef(newDest[i], src[i])
}
return newDest
}
func (orig *EntityRef) Reset() {
*orig = EntityRef{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *EntityRef) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.SchemaUrl != "" {
dest.WriteObjectField("schemaUrl")
dest.WriteString(orig.SchemaUrl)
}
if orig.Type != "" {
dest.WriteObjectField("type")
dest.WriteString(orig.Type)
}
if len(orig.IdKeys) > 0 {
dest.WriteObjectField("idKeys")
dest.WriteArrayStart()
dest.WriteString(orig.IdKeys[0])
for i := 1; i < len(orig.IdKeys); i++ {
dest.WriteMore()
dest.WriteString(orig.IdKeys[i])
}
dest.WriteArrayEnd()
}
if len(orig.DescriptionKeys) > 0 {
dest.WriteObjectField("descriptionKeys")
dest.WriteArrayStart()
dest.WriteString(orig.DescriptionKeys[0])
for i := 1; i < len(orig.DescriptionKeys); i++ {
dest.WriteMore()
dest.WriteString(orig.DescriptionKeys[i])
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *EntityRef) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "schemaUrl", "schema_url":
orig.SchemaUrl = iter.ReadString()
case "type":
orig.Type = iter.ReadString()
case "idKeys", "id_keys":
for iter.ReadArray() {
orig.IdKeys = append(orig.IdKeys, iter.ReadString())
}
case "descriptionKeys", "description_keys":
for iter.ReadArray() {
orig.DescriptionKeys = append(orig.DescriptionKeys, iter.ReadString())
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *EntityRef) SizeProto() int {
var n int
var l int
_ = l
l = len(orig.SchemaUrl)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.Type)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
for _, s := range orig.IdKeys {
l = len(s)
n += 1 + proto.Sov(uint64(l)) + l
}
for _, s := range orig.DescriptionKeys {
l = len(s)
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *EntityRef) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = len(orig.SchemaUrl)
if l > 0 {
pos -= l
copy(buf[pos:], orig.SchemaUrl)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
l = len(orig.Type)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Type)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
for i := len(orig.IdKeys) - 1; i >= 0; i-- {
l = len(orig.IdKeys[i])
pos -= l
copy(buf[pos:], orig.IdKeys[i])
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
for i := len(orig.DescriptionKeys) - 1; i >= 0; i-- {
l = len(orig.DescriptionKeys[i])
pos -= l
copy(buf[pos:], orig.DescriptionKeys[i])
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x22
}
return len(buf) - pos
}
func (orig *EntityRef) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SchemaUrl", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SchemaUrl = string(buf[startPos:pos])
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Type = string(buf[startPos:pos])
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field IdKeys", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.IdKeys = append(orig.IdKeys, string(buf[startPos:pos]))
case 4:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field DescriptionKeys", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.DescriptionKeys = append(orig.DescriptionKeys, string(buf[startPos:pos]))
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestEntityRef() *EntityRef {
orig := NewEntityRef()
orig.SchemaUrl = "test_schemaurl"
orig.Type = "test_type"
orig.IdKeys = []string{"", "test_idkeys"}
orig.DescriptionKeys = []string{"", "test_descriptionkeys"}
return orig
}
func GenTestEntityRefPtrSlice() []*EntityRef {
orig := make([]*EntityRef, 5)
orig[0] = NewEntityRef()
orig[1] = GenTestEntityRef()
orig[2] = NewEntityRef()
orig[3] = GenTestEntityRef()
orig[4] = NewEntityRef()
return orig
}
func GenTestEntityRefSlice() []EntityRef {
orig := make([]EntityRef, 5)
orig[1] = *GenTestEntityRef()
orig[3] = *GenTestEntityRef()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"math"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
func (m *Exemplar) GetValue() any {
if m != nil {
return m.Value
}
return nil
}
func (m *Exemplar) deleteValue() {
if m == nil {
return
}
switch ov := m.Value.(type) {
case *Exemplar_AsDouble:
deleteExemplar_AsDouble(ov)
case *Exemplar_AsInt:
deleteExemplar_AsInt(ov)
}
m.Value = nil
}
var (
protoPoolExemplar_AsDouble = sync.Pool{
New: func() any {
return &Exemplar_AsDouble{}
},
}
)
type Exemplar_AsDouble struct {
AsDouble float64
}
func NewExemplar_AsDouble() *Exemplar_AsDouble {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Exemplar_AsDouble{}
}
return protoPoolExemplar_AsDouble.Get().(*Exemplar_AsDouble)
}
func deleteExemplar_AsDouble(v *Exemplar_AsDouble) {
// Called only when pool is enabled
v.AsDouble = float64(0)
protoPoolExemplar_AsDouble.Put(v)
}
func (m *Exemplar) GetAsDouble() float64 {
if v, ok := m.GetValue().(*Exemplar_AsDouble); ok {
return v.AsDouble
}
return float64(0)
}
func (m *Exemplar) SetAsDouble(val float64) {
if m.Value != nil {
// Reuse message if possible, otherwise delete and create a new one.
if v, ok := m.GetValue().(*Exemplar_AsDouble); ok {
v.AsDouble = val
return
}
m.deleteValue()
}
v := NewExemplar_AsDouble()
v.AsDouble = val
m.Value = v
}
var (
protoPoolExemplar_AsInt = sync.Pool{
New: func() any {
return &Exemplar_AsInt{}
},
}
)
type Exemplar_AsInt struct {
AsInt int64
}
func NewExemplar_AsInt() *Exemplar_AsInt {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Exemplar_AsInt{}
}
return protoPoolExemplar_AsInt.Get().(*Exemplar_AsInt)
}
func deleteExemplar_AsInt(v *Exemplar_AsInt) {
// Called only when pool is enabled
v.AsInt = int64(0)
protoPoolExemplar_AsInt.Put(v)
}
func (m *Exemplar) GetAsInt() int64 {
if v, ok := m.GetValue().(*Exemplar_AsInt); ok {
return v.AsInt
}
return int64(0)
}
func (m *Exemplar) SetAsInt(val int64) {
if m.Value != nil {
// Reuse message if possible, otherwise delete and create a new one.
if v, ok := m.GetValue().(*Exemplar_AsInt); ok {
v.AsInt = val
return
}
m.deleteValue()
}
v := NewExemplar_AsInt()
v.AsInt = val
m.Value = v
}
// Exemplar is a sample input double measurement.
//
// Exemplars also hold information about the environment when the measurement was recorded,
// for example the span and trace ID of the active span when the exemplar was recorded.
type Exemplar struct {
Value any
FilteredAttributes []KeyValue
TimeUnixNano uint64
TraceId TraceID
SpanId SpanID
}
var (
protoPoolExemplar = sync.Pool{
New: func() any {
return &Exemplar{}
},
}
)
func NewExemplar() *Exemplar {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Exemplar{}
}
return protoPoolExemplar.Get().(*Exemplar)
}
func DeleteExemplar(orig *Exemplar, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.FilteredAttributes {
DeleteKeyValue(&orig.FilteredAttributes[i], false)
}
orig.deleteValue()
DeleteTraceID(&orig.TraceId, false)
DeleteSpanID(&orig.SpanId, false)
orig.Reset()
if nullable {
protoPoolExemplar.Put(orig)
}
}
func CopyExemplar(dest, src *Exemplar) *Exemplar {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExemplar()
}
dest.FilteredAttributes = CopyKeyValueSlice(dest.FilteredAttributes, src.FilteredAttributes)
dest.TimeUnixNano = src.TimeUnixNano
switch t := src.Value.(type) {
case *Exemplar_AsDouble:
ov := NewExemplar_AsDouble()
ov.AsDouble = t.AsDouble
dest.Value = ov
case *Exemplar_AsInt:
ov := NewExemplar_AsInt()
ov.AsInt = t.AsInt
dest.Value = ov
default:
dest.Value = nil
}
CopyTraceID(&dest.TraceId, &src.TraceId)
CopySpanID(&dest.SpanId, &src.SpanId)
return dest
}
func CopyExemplarSlice(dest, src []Exemplar) []Exemplar {
var newDest []Exemplar
if cap(dest) < len(src) {
newDest = make([]Exemplar, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExemplar(&dest[i], false)
}
}
for i := range src {
CopyExemplar(&newDest[i], &src[i])
}
return newDest
}
func CopyExemplarPtrSlice(dest, src []*Exemplar) []*Exemplar {
var newDest []*Exemplar
if cap(dest) < len(src) {
newDest = make([]*Exemplar, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExemplar()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExemplar(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExemplar()
}
}
for i := range src {
CopyExemplar(newDest[i], src[i])
}
return newDest
}
func (orig *Exemplar) Reset() {
*orig = Exemplar{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Exemplar) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.FilteredAttributes) > 0 {
dest.WriteObjectField("filteredAttributes")
dest.WriteArrayStart()
orig.FilteredAttributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.FilteredAttributes); i++ {
dest.WriteMore()
orig.FilteredAttributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.TimeUnixNano != uint64(0) {
dest.WriteObjectField("timeUnixNano")
dest.WriteUint64(orig.TimeUnixNano)
}
switch orig := orig.Value.(type) {
case *Exemplar_AsDouble:
dest.WriteObjectField("asDouble")
dest.WriteFloat64(orig.AsDouble)
case *Exemplar_AsInt:
dest.WriteObjectField("asInt")
dest.WriteInt64(orig.AsInt)
}
if !orig.TraceId.IsEmpty() {
dest.WriteObjectField("traceId")
orig.TraceId.MarshalJSON(dest)
}
if !orig.SpanId.IsEmpty() {
dest.WriteObjectField("spanId")
orig.SpanId.MarshalJSON(dest)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Exemplar) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "filteredAttributes", "filtered_attributes":
for iter.ReadArray() {
orig.FilteredAttributes = append(orig.FilteredAttributes, KeyValue{})
orig.FilteredAttributes[len(orig.FilteredAttributes)-1].UnmarshalJSON(iter)
}
case "timeUnixNano", "time_unix_nano":
orig.TimeUnixNano = iter.ReadUint64()
case "asDouble", "as_double":
{
ov := NewExemplar_AsDouble()
ov.AsDouble = iter.ReadFloat64()
orig.Value = ov
}
case "asInt", "as_int":
{
ov := NewExemplar_AsInt()
ov.AsInt = iter.ReadInt64()
orig.Value = ov
}
case "traceId", "trace_id":
orig.TraceId.UnmarshalJSON(iter)
case "spanId", "span_id":
orig.SpanId.UnmarshalJSON(iter)
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Exemplar) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.FilteredAttributes {
l = orig.FilteredAttributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.TimeUnixNano != uint64(0) {
n += 9
}
switch orig := orig.Value.(type) {
case nil:
_ = orig
break
case *Exemplar_AsDouble:
n += 9
case *Exemplar_AsInt:
n += 9
}
l = orig.TraceId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
l = orig.SpanId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
return n
}
func (orig *Exemplar) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.FilteredAttributes) - 1; i >= 0; i-- {
l = orig.FilteredAttributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x3a
}
if orig.TimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))
pos--
buf[pos] = 0x11
}
switch orig := orig.Value.(type) {
case *Exemplar_AsDouble:
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.AsDouble))
pos--
buf[pos] = 0x19
case *Exemplar_AsInt:
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.AsInt))
pos--
buf[pos] = 0x31
}
l = orig.TraceId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x2a
l = orig.SpanId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x22
return len(buf) - pos
}
func (orig *Exemplar) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 7:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field FilteredAttributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.FilteredAttributes = append(orig.FilteredAttributes, KeyValue{})
err = orig.FilteredAttributes[len(orig.FilteredAttributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field TimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.TimeUnixNano = uint64(num)
case 3:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field AsDouble", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
ov := NewExemplar_AsDouble()
ov.AsDouble = math.Float64frombits(num)
orig.Value = ov
case 6:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field AsInt", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
ov := NewExemplar_AsInt()
ov.AsInt = int64(num)
orig.Value = ov
case 5:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TraceId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.TraceId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 4:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SpanId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.SpanId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExemplar() *Exemplar {
orig := NewExemplar()
orig.FilteredAttributes = []KeyValue{{}, *GenTestKeyValue()}
orig.TimeUnixNano = uint64(13)
orig.Value = &Exemplar_AsDouble{AsDouble: float64(3.1415926)}
orig.TraceId = *GenTestTraceID()
orig.SpanId = *GenTestSpanID()
return orig
}
func GenTestExemplarPtrSlice() []*Exemplar {
orig := make([]*Exemplar, 5)
orig[0] = NewExemplar()
orig[1] = GenTestExemplar()
orig[2] = NewExemplar()
orig[3] = GenTestExemplar()
orig[4] = NewExemplar()
return orig
}
func GenTestExemplarSlice() []Exemplar {
orig := make([]Exemplar, 5)
orig[1] = *GenTestExemplar()
orig[3] = *GenTestExemplar()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExponentialHistogram represents the type of a metric that is calculated by aggregating
// as a ExponentialHistogram of all reported double measurements over a time interval.
type ExponentialHistogram struct {
DataPoints []*ExponentialHistogramDataPoint
AggregationTemporality AggregationTemporality
}
var (
protoPoolExponentialHistogram = sync.Pool{
New: func() any {
return &ExponentialHistogram{}
},
}
)
func NewExponentialHistogram() *ExponentialHistogram {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExponentialHistogram{}
}
return protoPoolExponentialHistogram.Get().(*ExponentialHistogram)
}
func DeleteExponentialHistogram(orig *ExponentialHistogram, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.DataPoints {
DeleteExponentialHistogramDataPoint(orig.DataPoints[i], true)
}
orig.Reset()
if nullable {
protoPoolExponentialHistogram.Put(orig)
}
}
func CopyExponentialHistogram(dest, src *ExponentialHistogram) *ExponentialHistogram {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExponentialHistogram()
}
dest.DataPoints = CopyExponentialHistogramDataPointPtrSlice(dest.DataPoints, src.DataPoints)
dest.AggregationTemporality = src.AggregationTemporality
return dest
}
func CopyExponentialHistogramSlice(dest, src []ExponentialHistogram) []ExponentialHistogram {
var newDest []ExponentialHistogram
if cap(dest) < len(src) {
newDest = make([]ExponentialHistogram, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExponentialHistogram(&dest[i], false)
}
}
for i := range src {
CopyExponentialHistogram(&newDest[i], &src[i])
}
return newDest
}
func CopyExponentialHistogramPtrSlice(dest, src []*ExponentialHistogram) []*ExponentialHistogram {
var newDest []*ExponentialHistogram
if cap(dest) < len(src) {
newDest = make([]*ExponentialHistogram, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExponentialHistogram()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExponentialHistogram(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExponentialHistogram()
}
}
for i := range src {
CopyExponentialHistogram(newDest[i], src[i])
}
return newDest
}
func (orig *ExponentialHistogram) Reset() {
*orig = ExponentialHistogram{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExponentialHistogram) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.DataPoints) > 0 {
dest.WriteObjectField("dataPoints")
dest.WriteArrayStart()
orig.DataPoints[0].MarshalJSON(dest)
for i := 1; i < len(orig.DataPoints); i++ {
dest.WriteMore()
orig.DataPoints[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if int32(orig.AggregationTemporality) != 0 {
dest.WriteObjectField("aggregationTemporality")
dest.WriteInt32(int32(orig.AggregationTemporality))
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExponentialHistogram) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "dataPoints", "data_points":
for iter.ReadArray() {
orig.DataPoints = append(orig.DataPoints, NewExponentialHistogramDataPoint())
orig.DataPoints[len(orig.DataPoints)-1].UnmarshalJSON(iter)
}
case "aggregationTemporality", "aggregation_temporality":
orig.AggregationTemporality = AggregationTemporality(iter.ReadEnumValue(AggregationTemporality_value))
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExponentialHistogram) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.DataPoints {
l = orig.DataPoints[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.AggregationTemporality != AggregationTemporality(0) {
n += 1 + proto.Sov(uint64(orig.AggregationTemporality))
}
return n
}
func (orig *ExponentialHistogram) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.DataPoints) - 1; i >= 0; i-- {
l = orig.DataPoints[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
if orig.AggregationTemporality != AggregationTemporality(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.AggregationTemporality))
pos--
buf[pos] = 0x10
}
return len(buf) - pos
}
func (orig *ExponentialHistogram) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field DataPoints", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.DataPoints = append(orig.DataPoints, NewExponentialHistogramDataPoint())
err = orig.DataPoints[len(orig.DataPoints)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field AggregationTemporality", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.AggregationTemporality = AggregationTemporality(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExponentialHistogram() *ExponentialHistogram {
orig := NewExponentialHistogram()
orig.DataPoints = []*ExponentialHistogramDataPoint{{}, GenTestExponentialHistogramDataPoint()}
orig.AggregationTemporality = AggregationTemporality(13)
return orig
}
func GenTestExponentialHistogramPtrSlice() []*ExponentialHistogram {
orig := make([]*ExponentialHistogram, 5)
orig[0] = NewExponentialHistogram()
orig[1] = GenTestExponentialHistogram()
orig[2] = NewExponentialHistogram()
orig[3] = GenTestExponentialHistogram()
orig[4] = NewExponentialHistogram()
return orig
}
func GenTestExponentialHistogramSlice() []ExponentialHistogram {
orig := make([]ExponentialHistogram, 5)
orig[1] = *GenTestExponentialHistogram()
orig[3] = *GenTestExponentialHistogram()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"math"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExponentialHistogramDataPoint is a single data point in a timeseries that describes the
// time-varying values of a ExponentialHistogram of double values. A ExponentialHistogram contains
// summary statistics for a population of values, it may optionally contain the
// distribution of those values across a set of buckets.
type ExponentialHistogramDataPoint struct {
Positive ExponentialHistogramDataPointBuckets
Negative ExponentialHistogramDataPointBuckets
Attributes []KeyValue
Exemplars []Exemplar
StartTimeUnixNano uint64
TimeUnixNano uint64
Count uint64
Sum float64
ZeroCount uint64
Min float64
Max float64
ZeroThreshold float64
metadata [1]uint64
Scale int32
Flags uint32
}
var (
protoPoolExponentialHistogramDataPoint = sync.Pool{
New: func() any {
return &ExponentialHistogramDataPoint{}
},
}
)
func NewExponentialHistogramDataPoint() *ExponentialHistogramDataPoint {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExponentialHistogramDataPoint{}
}
return protoPoolExponentialHistogramDataPoint.Get().(*ExponentialHistogramDataPoint)
}
func DeleteExponentialHistogramDataPoint(orig *ExponentialHistogramDataPoint, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.Attributes {
DeleteKeyValue(&orig.Attributes[i], false)
}
DeleteExponentialHistogramDataPointBuckets(&orig.Positive, false)
DeleteExponentialHistogramDataPointBuckets(&orig.Negative, false)
for i := range orig.Exemplars {
DeleteExemplar(&orig.Exemplars[i], false)
}
orig.Reset()
if nullable {
protoPoolExponentialHistogramDataPoint.Put(orig)
}
}
func CopyExponentialHistogramDataPoint(dest, src *ExponentialHistogramDataPoint) *ExponentialHistogramDataPoint {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExponentialHistogramDataPoint()
}
dest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)
dest.StartTimeUnixNano = src.StartTimeUnixNano
dest.TimeUnixNano = src.TimeUnixNano
dest.Count = src.Count
if src.HasSum() {
dest.SetSum(src.Sum)
} else {
dest.RemoveSum()
}
dest.Scale = src.Scale
dest.ZeroCount = src.ZeroCount
CopyExponentialHistogramDataPointBuckets(&dest.Positive, &src.Positive)
CopyExponentialHistogramDataPointBuckets(&dest.Negative, &src.Negative)
dest.Flags = src.Flags
dest.Exemplars = CopyExemplarSlice(dest.Exemplars, src.Exemplars)
if src.HasMin() {
dest.SetMin(src.Min)
} else {
dest.RemoveMin()
}
if src.HasMax() {
dest.SetMax(src.Max)
} else {
dest.RemoveMax()
}
dest.ZeroThreshold = src.ZeroThreshold
return dest
}
func CopyExponentialHistogramDataPointSlice(dest, src []ExponentialHistogramDataPoint) []ExponentialHistogramDataPoint {
var newDest []ExponentialHistogramDataPoint
if cap(dest) < len(src) {
newDest = make([]ExponentialHistogramDataPoint, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExponentialHistogramDataPoint(&dest[i], false)
}
}
for i := range src {
CopyExponentialHistogramDataPoint(&newDest[i], &src[i])
}
return newDest
}
func CopyExponentialHistogramDataPointPtrSlice(dest, src []*ExponentialHistogramDataPoint) []*ExponentialHistogramDataPoint {
var newDest []*ExponentialHistogramDataPoint
if cap(dest) < len(src) {
newDest = make([]*ExponentialHistogramDataPoint, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExponentialHistogramDataPoint()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExponentialHistogramDataPoint(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExponentialHistogramDataPoint()
}
}
for i := range src {
CopyExponentialHistogramDataPoint(newDest[i], src[i])
}
return newDest
}
func (orig *ExponentialHistogramDataPoint) Reset() {
*orig = ExponentialHistogramDataPoint{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExponentialHistogramDataPoint) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.Attributes) > 0 {
dest.WriteObjectField("attributes")
dest.WriteArrayStart()
orig.Attributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.Attributes); i++ {
dest.WriteMore()
orig.Attributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.StartTimeUnixNano != uint64(0) {
dest.WriteObjectField("startTimeUnixNano")
dest.WriteUint64(orig.StartTimeUnixNano)
}
if orig.TimeUnixNano != uint64(0) {
dest.WriteObjectField("timeUnixNano")
dest.WriteUint64(orig.TimeUnixNano)
}
if orig.Count != uint64(0) {
dest.WriteObjectField("count")
dest.WriteUint64(orig.Count)
}
if orig.HasSum() {
dest.WriteObjectField("sum")
dest.WriteFloat64(orig.Sum)
}
if orig.Scale != int32(0) {
dest.WriteObjectField("scale")
dest.WriteInt32(orig.Scale)
}
if orig.ZeroCount != uint64(0) {
dest.WriteObjectField("zeroCount")
dest.WriteUint64(orig.ZeroCount)
}
dest.WriteObjectField("positive")
orig.Positive.MarshalJSON(dest)
dest.WriteObjectField("negative")
orig.Negative.MarshalJSON(dest)
if orig.Flags != uint32(0) {
dest.WriteObjectField("flags")
dest.WriteUint32(orig.Flags)
}
if len(orig.Exemplars) > 0 {
dest.WriteObjectField("exemplars")
dest.WriteArrayStart()
orig.Exemplars[0].MarshalJSON(dest)
for i := 1; i < len(orig.Exemplars); i++ {
dest.WriteMore()
orig.Exemplars[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.HasMin() {
dest.WriteObjectField("min")
dest.WriteFloat64(orig.Min)
}
if orig.HasMax() {
dest.WriteObjectField("max")
dest.WriteFloat64(orig.Max)
}
if orig.ZeroThreshold != float64(0) {
dest.WriteObjectField("zeroThreshold")
dest.WriteFloat64(orig.ZeroThreshold)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExponentialHistogramDataPoint) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "attributes":
for iter.ReadArray() {
orig.Attributes = append(orig.Attributes, KeyValue{})
orig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)
}
case "startTimeUnixNano", "start_time_unix_nano":
orig.StartTimeUnixNano = iter.ReadUint64()
case "timeUnixNano", "time_unix_nano":
orig.TimeUnixNano = iter.ReadUint64()
case "count":
orig.Count = iter.ReadUint64()
case "sum":
orig.SetSum(iter.ReadFloat64())
case "scale":
orig.Scale = iter.ReadInt32()
case "zeroCount", "zero_count":
orig.ZeroCount = iter.ReadUint64()
case "positive":
orig.Positive.UnmarshalJSON(iter)
case "negative":
orig.Negative.UnmarshalJSON(iter)
case "flags":
orig.Flags = iter.ReadUint32()
case "exemplars":
for iter.ReadArray() {
orig.Exemplars = append(orig.Exemplars, Exemplar{})
orig.Exemplars[len(orig.Exemplars)-1].UnmarshalJSON(iter)
}
case "min":
orig.SetMin(iter.ReadFloat64())
case "max":
orig.SetMax(iter.ReadFloat64())
case "zeroThreshold", "zero_threshold":
orig.ZeroThreshold = iter.ReadFloat64()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExponentialHistogramDataPoint) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.Attributes {
l = orig.Attributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.StartTimeUnixNano != uint64(0) {
n += 9
}
if orig.TimeUnixNano != uint64(0) {
n += 9
}
if orig.Count != uint64(0) {
n += 9
}
if orig.HasSum() {
n += 9
}
if orig.Scale != int32(0) {
n += 1 + proto.Soz(uint64(orig.Scale))
}
if orig.ZeroCount != uint64(0) {
n += 9
}
l = orig.Positive.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
l = orig.Negative.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.Flags != uint32(0) {
n += 1 + proto.Sov(uint64(orig.Flags))
}
for i := range orig.Exemplars {
l = orig.Exemplars[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.HasMin() {
n += 9
}
if orig.HasMax() {
n += 9
}
if orig.ZeroThreshold != float64(0) {
n += 9
}
return n
}
func (orig *ExponentialHistogramDataPoint) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.Attributes) - 1; i >= 0; i-- {
l = orig.Attributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
if orig.StartTimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.StartTimeUnixNano))
pos--
buf[pos] = 0x11
}
if orig.TimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))
pos--
buf[pos] = 0x19
}
if orig.Count != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.Count))
pos--
buf[pos] = 0x21
}
if orig.HasSum() {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Sum))
pos--
buf[pos] = 0x29
}
if orig.Scale != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64((uint32(orig.Scale)<<1)^uint32(orig.Scale>>31)))
pos--
buf[pos] = 0x30
}
if orig.ZeroCount != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.ZeroCount))
pos--
buf[pos] = 0x39
}
l = orig.Positive.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x42
l = orig.Negative.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x4a
if orig.Flags != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Flags))
pos--
buf[pos] = 0x50
}
for i := len(orig.Exemplars) - 1; i >= 0; i-- {
l = orig.Exemplars[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x5a
}
if orig.HasMin() {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Min))
pos--
buf[pos] = 0x61
}
if orig.HasMax() {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Max))
pos--
buf[pos] = 0x69
}
if orig.ZeroThreshold != float64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.ZeroThreshold))
pos--
buf[pos] = 0x71
}
return len(buf) - pos
}
func (orig *ExponentialHistogramDataPoint) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Attributes = append(orig.Attributes, KeyValue{})
err = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field StartTimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.StartTimeUnixNano = uint64(num)
case 3:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field TimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.TimeUnixNano = uint64(num)
case 4:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Count", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.Count = uint64(num)
case 5:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Sum", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.SetSum(math.Float64frombits(num))
case 6:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Scale", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Scale = int32(uint32(num>>1) ^ uint32(int32((num&1)<<31)>>31))
case 7:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field ZeroCount", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.ZeroCount = uint64(num)
case 8:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Positive", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Positive.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 9:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Negative", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Negative.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 10:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Flags", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Flags = uint32(num)
case 11:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Exemplars", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Exemplars = append(orig.Exemplars, Exemplar{})
err = orig.Exemplars[len(orig.Exemplars)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 12:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Min", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.SetMin(math.Float64frombits(num))
case 13:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Max", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.SetMax(math.Float64frombits(num))
case 14:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field ZeroThreshold", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.ZeroThreshold = math.Float64frombits(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
const fieldBlockExponentialHistogramDataPointSum = uint64(0 >> 6)
const fieldBitExponentialHistogramDataPointSum = uint64(1 << 0 & 0x3F)
func (m *ExponentialHistogramDataPoint) SetSum(value float64) {
m.Sum = value
m.metadata[fieldBlockExponentialHistogramDataPointSum] |= fieldBitExponentialHistogramDataPointSum
}
func (m *ExponentialHistogramDataPoint) RemoveSum() {
m.Sum = float64(0)
m.metadata[fieldBlockExponentialHistogramDataPointSum] &^= fieldBitExponentialHistogramDataPointSum
}
func (m *ExponentialHistogramDataPoint) HasSum() bool {
return m.metadata[fieldBlockExponentialHistogramDataPointSum]&fieldBitExponentialHistogramDataPointSum != 0
}
const fieldBlockExponentialHistogramDataPointMin = uint64(1 >> 6)
const fieldBitExponentialHistogramDataPointMin = uint64(1 << 1 & 0x3F)
func (m *ExponentialHistogramDataPoint) SetMin(value float64) {
m.Min = value
m.metadata[fieldBlockExponentialHistogramDataPointMin] |= fieldBitExponentialHistogramDataPointMin
}
func (m *ExponentialHistogramDataPoint) RemoveMin() {
m.Min = float64(0)
m.metadata[fieldBlockExponentialHistogramDataPointMin] &^= fieldBitExponentialHistogramDataPointMin
}
func (m *ExponentialHistogramDataPoint) HasMin() bool {
return m.metadata[fieldBlockExponentialHistogramDataPointMin]&fieldBitExponentialHistogramDataPointMin != 0
}
const fieldBlockExponentialHistogramDataPointMax = uint64(2 >> 6)
const fieldBitExponentialHistogramDataPointMax = uint64(1 << 2 & 0x3F)
func (m *ExponentialHistogramDataPoint) SetMax(value float64) {
m.Max = value
m.metadata[fieldBlockExponentialHistogramDataPointMax] |= fieldBitExponentialHistogramDataPointMax
}
func (m *ExponentialHistogramDataPoint) RemoveMax() {
m.Max = float64(0)
m.metadata[fieldBlockExponentialHistogramDataPointMax] &^= fieldBitExponentialHistogramDataPointMax
}
func (m *ExponentialHistogramDataPoint) HasMax() bool {
return m.metadata[fieldBlockExponentialHistogramDataPointMax]&fieldBitExponentialHistogramDataPointMax != 0
}
func GenTestExponentialHistogramDataPoint() *ExponentialHistogramDataPoint {
orig := NewExponentialHistogramDataPoint()
orig.Attributes = []KeyValue{{}, *GenTestKeyValue()}
orig.StartTimeUnixNano = uint64(13)
orig.TimeUnixNano = uint64(13)
orig.Count = uint64(13)
orig.SetSum(float64(3.1415926))
orig.Scale = int32(13)
orig.ZeroCount = uint64(13)
orig.Positive = *GenTestExponentialHistogramDataPointBuckets()
orig.Negative = *GenTestExponentialHistogramDataPointBuckets()
orig.Flags = uint32(13)
orig.Exemplars = []Exemplar{{}, *GenTestExemplar()}
orig.SetMin(float64(3.1415926))
orig.SetMax(float64(3.1415926))
orig.ZeroThreshold = float64(3.1415926)
return orig
}
func GenTestExponentialHistogramDataPointPtrSlice() []*ExponentialHistogramDataPoint {
orig := make([]*ExponentialHistogramDataPoint, 5)
orig[0] = NewExponentialHistogramDataPoint()
orig[1] = GenTestExponentialHistogramDataPoint()
orig[2] = NewExponentialHistogramDataPoint()
orig[3] = GenTestExponentialHistogramDataPoint()
orig[4] = NewExponentialHistogramDataPoint()
return orig
}
func GenTestExponentialHistogramDataPointSlice() []ExponentialHistogramDataPoint {
orig := make([]ExponentialHistogramDataPoint, 5)
orig[1] = *GenTestExponentialHistogramDataPoint()
orig[3] = *GenTestExponentialHistogramDataPoint()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExponentialHistogramDataPointBuckets are a set of bucket counts, encoded in a contiguous array of counts.
type ExponentialHistogramDataPointBuckets struct {
BucketCounts []uint64
Offset int32
}
var (
protoPoolExponentialHistogramDataPointBuckets = sync.Pool{
New: func() any {
return &ExponentialHistogramDataPointBuckets{}
},
}
)
func NewExponentialHistogramDataPointBuckets() *ExponentialHistogramDataPointBuckets {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExponentialHistogramDataPointBuckets{}
}
return protoPoolExponentialHistogramDataPointBuckets.Get().(*ExponentialHistogramDataPointBuckets)
}
func DeleteExponentialHistogramDataPointBuckets(orig *ExponentialHistogramDataPointBuckets, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolExponentialHistogramDataPointBuckets.Put(orig)
}
}
func CopyExponentialHistogramDataPointBuckets(dest, src *ExponentialHistogramDataPointBuckets) *ExponentialHistogramDataPointBuckets {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExponentialHistogramDataPointBuckets()
}
dest.Offset = src.Offset
dest.BucketCounts = append(dest.BucketCounts[:0], src.BucketCounts...)
return dest
}
func CopyExponentialHistogramDataPointBucketsSlice(dest, src []ExponentialHistogramDataPointBuckets) []ExponentialHistogramDataPointBuckets {
var newDest []ExponentialHistogramDataPointBuckets
if cap(dest) < len(src) {
newDest = make([]ExponentialHistogramDataPointBuckets, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExponentialHistogramDataPointBuckets(&dest[i], false)
}
}
for i := range src {
CopyExponentialHistogramDataPointBuckets(&newDest[i], &src[i])
}
return newDest
}
func CopyExponentialHistogramDataPointBucketsPtrSlice(dest, src []*ExponentialHistogramDataPointBuckets) []*ExponentialHistogramDataPointBuckets {
var newDest []*ExponentialHistogramDataPointBuckets
if cap(dest) < len(src) {
newDest = make([]*ExponentialHistogramDataPointBuckets, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExponentialHistogramDataPointBuckets()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExponentialHistogramDataPointBuckets(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExponentialHistogramDataPointBuckets()
}
}
for i := range src {
CopyExponentialHistogramDataPointBuckets(newDest[i], src[i])
}
return newDest
}
func (orig *ExponentialHistogramDataPointBuckets) Reset() {
*orig = ExponentialHistogramDataPointBuckets{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExponentialHistogramDataPointBuckets) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.Offset != int32(0) {
dest.WriteObjectField("offset")
dest.WriteInt32(orig.Offset)
}
if len(orig.BucketCounts) > 0 {
dest.WriteObjectField("bucketCounts")
dest.WriteArrayStart()
dest.WriteUint64(orig.BucketCounts[0])
for i := 1; i < len(orig.BucketCounts); i++ {
dest.WriteMore()
dest.WriteUint64(orig.BucketCounts[i])
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExponentialHistogramDataPointBuckets) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "offset":
orig.Offset = iter.ReadInt32()
case "bucketCounts", "bucket_counts":
for iter.ReadArray() {
orig.BucketCounts = append(orig.BucketCounts, iter.ReadUint64())
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExponentialHistogramDataPointBuckets) SizeProto() int {
var n int
var l int
_ = l
if orig.Offset != int32(0) {
n += 1 + proto.Soz(uint64(orig.Offset))
}
if len(orig.BucketCounts) > 0 {
l = 0
for _, e := range orig.BucketCounts {
l += proto.Sov(uint64(e))
}
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ExponentialHistogramDataPointBuckets) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.Offset != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64((uint32(orig.Offset)<<1)^uint32(orig.Offset>>31)))
pos--
buf[pos] = 0x8
}
l = len(orig.BucketCounts)
if l > 0 {
endPos := pos
for i := l - 1; i >= 0; i-- {
pos = proto.EncodeVarint(buf, pos, uint64(orig.BucketCounts[i]))
}
pos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))
pos--
buf[pos] = 0x12
}
return len(buf) - pos
}
func (orig *ExponentialHistogramDataPointBuckets) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Offset", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Offset = int32(uint32(num>>1) ^ uint32(int32((num&1)<<31)>>31))
case 2:
switch wireType {
case proto.WireTypeLen:
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
var num uint64
for startPos < pos {
num, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)
if err != nil {
return err
}
orig.BucketCounts = append(orig.BucketCounts, uint64(num))
}
if startPos != pos {
return fmt.Errorf("proto: invalid field len = %d for field BucketCounts", pos-startPos)
}
case proto.WireTypeVarint:
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.BucketCounts = append(orig.BucketCounts, uint64(num))
default:
return fmt.Errorf("proto: wrong wireType = %d for field BucketCounts", wireType)
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExponentialHistogramDataPointBuckets() *ExponentialHistogramDataPointBuckets {
orig := NewExponentialHistogramDataPointBuckets()
orig.Offset = int32(13)
orig.BucketCounts = []uint64{uint64(0), uint64(13)}
return orig
}
func GenTestExponentialHistogramDataPointBucketsPtrSlice() []*ExponentialHistogramDataPointBuckets {
orig := make([]*ExponentialHistogramDataPointBuckets, 5)
orig[0] = NewExponentialHistogramDataPointBuckets()
orig[1] = GenTestExponentialHistogramDataPointBuckets()
orig[2] = NewExponentialHistogramDataPointBuckets()
orig[3] = GenTestExponentialHistogramDataPointBuckets()
orig[4] = NewExponentialHistogramDataPointBuckets()
return orig
}
func GenTestExponentialHistogramDataPointBucketsSlice() []ExponentialHistogramDataPointBuckets {
orig := make([]ExponentialHistogramDataPointBuckets, 5)
orig[1] = *GenTestExponentialHistogramDataPointBuckets()
orig[3] = *GenTestExponentialHistogramDataPointBuckets()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExportPartialSuccess represents the details of a partially successful export request.
type ExportLogsPartialSuccess struct {
ErrorMessage string
RejectedLogRecords int64
}
var (
protoPoolExportLogsPartialSuccess = sync.Pool{
New: func() any {
return &ExportLogsPartialSuccess{}
},
}
)
func NewExportLogsPartialSuccess() *ExportLogsPartialSuccess {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportLogsPartialSuccess{}
}
return protoPoolExportLogsPartialSuccess.Get().(*ExportLogsPartialSuccess)
}
func DeleteExportLogsPartialSuccess(orig *ExportLogsPartialSuccess, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolExportLogsPartialSuccess.Put(orig)
}
}
func CopyExportLogsPartialSuccess(dest, src *ExportLogsPartialSuccess) *ExportLogsPartialSuccess {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportLogsPartialSuccess()
}
dest.RejectedLogRecords = src.RejectedLogRecords
dest.ErrorMessage = src.ErrorMessage
return dest
}
func CopyExportLogsPartialSuccessSlice(dest, src []ExportLogsPartialSuccess) []ExportLogsPartialSuccess {
var newDest []ExportLogsPartialSuccess
if cap(dest) < len(src) {
newDest = make([]ExportLogsPartialSuccess, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportLogsPartialSuccess(&dest[i], false)
}
}
for i := range src {
CopyExportLogsPartialSuccess(&newDest[i], &src[i])
}
return newDest
}
func CopyExportLogsPartialSuccessPtrSlice(dest, src []*ExportLogsPartialSuccess) []*ExportLogsPartialSuccess {
var newDest []*ExportLogsPartialSuccess
if cap(dest) < len(src) {
newDest = make([]*ExportLogsPartialSuccess, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportLogsPartialSuccess()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportLogsPartialSuccess(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportLogsPartialSuccess()
}
}
for i := range src {
CopyExportLogsPartialSuccess(newDest[i], src[i])
}
return newDest
}
func (orig *ExportLogsPartialSuccess) Reset() {
*orig = ExportLogsPartialSuccess{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportLogsPartialSuccess) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.RejectedLogRecords != int64(0) {
dest.WriteObjectField("rejectedLogRecords")
dest.WriteInt64(orig.RejectedLogRecords)
}
if orig.ErrorMessage != "" {
dest.WriteObjectField("errorMessage")
dest.WriteString(orig.ErrorMessage)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportLogsPartialSuccess) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "rejectedLogRecords", "rejected_log_records":
orig.RejectedLogRecords = iter.ReadInt64()
case "errorMessage", "error_message":
orig.ErrorMessage = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportLogsPartialSuccess) SizeProto() int {
var n int
var l int
_ = l
if orig.RejectedLogRecords != int64(0) {
n += 1 + proto.Sov(uint64(orig.RejectedLogRecords))
}
l = len(orig.ErrorMessage)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ExportLogsPartialSuccess) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.RejectedLogRecords != int64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.RejectedLogRecords))
pos--
buf[pos] = 0x8
}
l = len(orig.ErrorMessage)
if l > 0 {
pos -= l
copy(buf[pos:], orig.ErrorMessage)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
return len(buf) - pos
}
func (orig *ExportLogsPartialSuccess) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field RejectedLogRecords", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.RejectedLogRecords = int64(num)
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ErrorMessage", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ErrorMessage = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportLogsPartialSuccess() *ExportLogsPartialSuccess {
orig := NewExportLogsPartialSuccess()
orig.RejectedLogRecords = int64(13)
orig.ErrorMessage = "test_errormessage"
return orig
}
func GenTestExportLogsPartialSuccessPtrSlice() []*ExportLogsPartialSuccess {
orig := make([]*ExportLogsPartialSuccess, 5)
orig[0] = NewExportLogsPartialSuccess()
orig[1] = GenTestExportLogsPartialSuccess()
orig[2] = NewExportLogsPartialSuccess()
orig[3] = GenTestExportLogsPartialSuccess()
orig[4] = NewExportLogsPartialSuccess()
return orig
}
func GenTestExportLogsPartialSuccessSlice() []ExportLogsPartialSuccess {
orig := make([]ExportLogsPartialSuccess, 5)
orig[1] = *GenTestExportLogsPartialSuccess()
orig[3] = *GenTestExportLogsPartialSuccess()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Logs is the top-level struct that is propagated through the logs pipeline.
// Use NewLogs to create new instance, zero-initialized instance is not valid for use.
type ExportLogsServiceRequest struct {
ResourceLogs []*ResourceLogs
}
var (
protoPoolExportLogsServiceRequest = sync.Pool{
New: func() any {
return &ExportLogsServiceRequest{}
},
}
)
func NewExportLogsServiceRequest() *ExportLogsServiceRequest {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportLogsServiceRequest{}
}
return protoPoolExportLogsServiceRequest.Get().(*ExportLogsServiceRequest)
}
func DeleteExportLogsServiceRequest(orig *ExportLogsServiceRequest, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.ResourceLogs {
DeleteResourceLogs(orig.ResourceLogs[i], true)
}
orig.Reset()
if nullable {
protoPoolExportLogsServiceRequest.Put(orig)
}
}
func CopyExportLogsServiceRequest(dest, src *ExportLogsServiceRequest) *ExportLogsServiceRequest {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportLogsServiceRequest()
}
dest.ResourceLogs = CopyResourceLogsPtrSlice(dest.ResourceLogs, src.ResourceLogs)
return dest
}
func CopyExportLogsServiceRequestSlice(dest, src []ExportLogsServiceRequest) []ExportLogsServiceRequest {
var newDest []ExportLogsServiceRequest
if cap(dest) < len(src) {
newDest = make([]ExportLogsServiceRequest, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportLogsServiceRequest(&dest[i], false)
}
}
for i := range src {
CopyExportLogsServiceRequest(&newDest[i], &src[i])
}
return newDest
}
func CopyExportLogsServiceRequestPtrSlice(dest, src []*ExportLogsServiceRequest) []*ExportLogsServiceRequest {
var newDest []*ExportLogsServiceRequest
if cap(dest) < len(src) {
newDest = make([]*ExportLogsServiceRequest, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportLogsServiceRequest()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportLogsServiceRequest(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportLogsServiceRequest()
}
}
for i := range src {
CopyExportLogsServiceRequest(newDest[i], src[i])
}
return newDest
}
func (orig *ExportLogsServiceRequest) Reset() {
*orig = ExportLogsServiceRequest{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportLogsServiceRequest) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.ResourceLogs) > 0 {
dest.WriteObjectField("resourceLogs")
dest.WriteArrayStart()
orig.ResourceLogs[0].MarshalJSON(dest)
for i := 1; i < len(orig.ResourceLogs); i++ {
dest.WriteMore()
orig.ResourceLogs[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportLogsServiceRequest) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resourceLogs", "resource_logs":
for iter.ReadArray() {
orig.ResourceLogs = append(orig.ResourceLogs, NewResourceLogs())
orig.ResourceLogs[len(orig.ResourceLogs)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportLogsServiceRequest) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.ResourceLogs {
l = orig.ResourceLogs[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ExportLogsServiceRequest) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.ResourceLogs) - 1; i >= 0; i-- {
l = orig.ResourceLogs[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *ExportLogsServiceRequest) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ResourceLogs", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ResourceLogs = append(orig.ResourceLogs, NewResourceLogs())
err = orig.ResourceLogs[len(orig.ResourceLogs)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportLogsServiceRequest() *ExportLogsServiceRequest {
orig := NewExportLogsServiceRequest()
orig.ResourceLogs = []*ResourceLogs{{}, GenTestResourceLogs()}
return orig
}
func GenTestExportLogsServiceRequestPtrSlice() []*ExportLogsServiceRequest {
orig := make([]*ExportLogsServiceRequest, 5)
orig[0] = NewExportLogsServiceRequest()
orig[1] = GenTestExportLogsServiceRequest()
orig[2] = NewExportLogsServiceRequest()
orig[3] = GenTestExportLogsServiceRequest()
orig[4] = NewExportLogsServiceRequest()
return orig
}
func GenTestExportLogsServiceRequestSlice() []ExportLogsServiceRequest {
orig := make([]ExportLogsServiceRequest, 5)
orig[1] = *GenTestExportLogsServiceRequest()
orig[3] = *GenTestExportLogsServiceRequest()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExportResponse represents the response for gRPC/HTTP client/server.
type ExportLogsServiceResponse struct {
PartialSuccess ExportLogsPartialSuccess
}
var (
protoPoolExportLogsServiceResponse = sync.Pool{
New: func() any {
return &ExportLogsServiceResponse{}
},
}
)
func NewExportLogsServiceResponse() *ExportLogsServiceResponse {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportLogsServiceResponse{}
}
return protoPoolExportLogsServiceResponse.Get().(*ExportLogsServiceResponse)
}
func DeleteExportLogsServiceResponse(orig *ExportLogsServiceResponse, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteExportLogsPartialSuccess(&orig.PartialSuccess, false)
orig.Reset()
if nullable {
protoPoolExportLogsServiceResponse.Put(orig)
}
}
func CopyExportLogsServiceResponse(dest, src *ExportLogsServiceResponse) *ExportLogsServiceResponse {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportLogsServiceResponse()
}
CopyExportLogsPartialSuccess(&dest.PartialSuccess, &src.PartialSuccess)
return dest
}
func CopyExportLogsServiceResponseSlice(dest, src []ExportLogsServiceResponse) []ExportLogsServiceResponse {
var newDest []ExportLogsServiceResponse
if cap(dest) < len(src) {
newDest = make([]ExportLogsServiceResponse, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportLogsServiceResponse(&dest[i], false)
}
}
for i := range src {
CopyExportLogsServiceResponse(&newDest[i], &src[i])
}
return newDest
}
func CopyExportLogsServiceResponsePtrSlice(dest, src []*ExportLogsServiceResponse) []*ExportLogsServiceResponse {
var newDest []*ExportLogsServiceResponse
if cap(dest) < len(src) {
newDest = make([]*ExportLogsServiceResponse, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportLogsServiceResponse()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportLogsServiceResponse(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportLogsServiceResponse()
}
}
for i := range src {
CopyExportLogsServiceResponse(newDest[i], src[i])
}
return newDest
}
func (orig *ExportLogsServiceResponse) Reset() {
*orig = ExportLogsServiceResponse{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportLogsServiceResponse) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("partialSuccess")
orig.PartialSuccess.MarshalJSON(dest)
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportLogsServiceResponse) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "partialSuccess", "partial_success":
orig.PartialSuccess.UnmarshalJSON(iter)
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportLogsServiceResponse) SizeProto() int {
var n int
var l int
_ = l
l = orig.PartialSuccess.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
return n
}
func (orig *ExportLogsServiceResponse) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.PartialSuccess.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
return len(buf) - pos
}
func (orig *ExportLogsServiceResponse) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field PartialSuccess", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.PartialSuccess.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportLogsServiceResponse() *ExportLogsServiceResponse {
orig := NewExportLogsServiceResponse()
orig.PartialSuccess = *GenTestExportLogsPartialSuccess()
return orig
}
func GenTestExportLogsServiceResponsePtrSlice() []*ExportLogsServiceResponse {
orig := make([]*ExportLogsServiceResponse, 5)
orig[0] = NewExportLogsServiceResponse()
orig[1] = GenTestExportLogsServiceResponse()
orig[2] = NewExportLogsServiceResponse()
orig[3] = GenTestExportLogsServiceResponse()
orig[4] = NewExportLogsServiceResponse()
return orig
}
func GenTestExportLogsServiceResponseSlice() []ExportLogsServiceResponse {
orig := make([]ExportLogsServiceResponse, 5)
orig[1] = *GenTestExportLogsServiceResponse()
orig[3] = *GenTestExportLogsServiceResponse()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExportPartialSuccess represents the details of a partially successful export request.
type ExportMetricsPartialSuccess struct {
ErrorMessage string
RejectedDataPoints int64
}
var (
protoPoolExportMetricsPartialSuccess = sync.Pool{
New: func() any {
return &ExportMetricsPartialSuccess{}
},
}
)
func NewExportMetricsPartialSuccess() *ExportMetricsPartialSuccess {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportMetricsPartialSuccess{}
}
return protoPoolExportMetricsPartialSuccess.Get().(*ExportMetricsPartialSuccess)
}
func DeleteExportMetricsPartialSuccess(orig *ExportMetricsPartialSuccess, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolExportMetricsPartialSuccess.Put(orig)
}
}
func CopyExportMetricsPartialSuccess(dest, src *ExportMetricsPartialSuccess) *ExportMetricsPartialSuccess {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportMetricsPartialSuccess()
}
dest.RejectedDataPoints = src.RejectedDataPoints
dest.ErrorMessage = src.ErrorMessage
return dest
}
func CopyExportMetricsPartialSuccessSlice(dest, src []ExportMetricsPartialSuccess) []ExportMetricsPartialSuccess {
var newDest []ExportMetricsPartialSuccess
if cap(dest) < len(src) {
newDest = make([]ExportMetricsPartialSuccess, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportMetricsPartialSuccess(&dest[i], false)
}
}
for i := range src {
CopyExportMetricsPartialSuccess(&newDest[i], &src[i])
}
return newDest
}
func CopyExportMetricsPartialSuccessPtrSlice(dest, src []*ExportMetricsPartialSuccess) []*ExportMetricsPartialSuccess {
var newDest []*ExportMetricsPartialSuccess
if cap(dest) < len(src) {
newDest = make([]*ExportMetricsPartialSuccess, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportMetricsPartialSuccess()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportMetricsPartialSuccess(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportMetricsPartialSuccess()
}
}
for i := range src {
CopyExportMetricsPartialSuccess(newDest[i], src[i])
}
return newDest
}
func (orig *ExportMetricsPartialSuccess) Reset() {
*orig = ExportMetricsPartialSuccess{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportMetricsPartialSuccess) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.RejectedDataPoints != int64(0) {
dest.WriteObjectField("rejectedDataPoints")
dest.WriteInt64(orig.RejectedDataPoints)
}
if orig.ErrorMessage != "" {
dest.WriteObjectField("errorMessage")
dest.WriteString(orig.ErrorMessage)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportMetricsPartialSuccess) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "rejectedDataPoints", "rejected_data_points":
orig.RejectedDataPoints = iter.ReadInt64()
case "errorMessage", "error_message":
orig.ErrorMessage = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportMetricsPartialSuccess) SizeProto() int {
var n int
var l int
_ = l
if orig.RejectedDataPoints != int64(0) {
n += 1 + proto.Sov(uint64(orig.RejectedDataPoints))
}
l = len(orig.ErrorMessage)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ExportMetricsPartialSuccess) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.RejectedDataPoints != int64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.RejectedDataPoints))
pos--
buf[pos] = 0x8
}
l = len(orig.ErrorMessage)
if l > 0 {
pos -= l
copy(buf[pos:], orig.ErrorMessage)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
return len(buf) - pos
}
func (orig *ExportMetricsPartialSuccess) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field RejectedDataPoints", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.RejectedDataPoints = int64(num)
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ErrorMessage", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ErrorMessage = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportMetricsPartialSuccess() *ExportMetricsPartialSuccess {
orig := NewExportMetricsPartialSuccess()
orig.RejectedDataPoints = int64(13)
orig.ErrorMessage = "test_errormessage"
return orig
}
func GenTestExportMetricsPartialSuccessPtrSlice() []*ExportMetricsPartialSuccess {
orig := make([]*ExportMetricsPartialSuccess, 5)
orig[0] = NewExportMetricsPartialSuccess()
orig[1] = GenTestExportMetricsPartialSuccess()
orig[2] = NewExportMetricsPartialSuccess()
orig[3] = GenTestExportMetricsPartialSuccess()
orig[4] = NewExportMetricsPartialSuccess()
return orig
}
func GenTestExportMetricsPartialSuccessSlice() []ExportMetricsPartialSuccess {
orig := make([]ExportMetricsPartialSuccess, 5)
orig[1] = *GenTestExportMetricsPartialSuccess()
orig[3] = *GenTestExportMetricsPartialSuccess()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Metrics is the top-level struct that is propagated through the metrics pipeline.
// Use NewMetrics to create new instance, zero-initialized instance is not valid for use.
type ExportMetricsServiceRequest struct {
ResourceMetrics []*ResourceMetrics
}
var (
protoPoolExportMetricsServiceRequest = sync.Pool{
New: func() any {
return &ExportMetricsServiceRequest{}
},
}
)
func NewExportMetricsServiceRequest() *ExportMetricsServiceRequest {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportMetricsServiceRequest{}
}
return protoPoolExportMetricsServiceRequest.Get().(*ExportMetricsServiceRequest)
}
func DeleteExportMetricsServiceRequest(orig *ExportMetricsServiceRequest, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.ResourceMetrics {
DeleteResourceMetrics(orig.ResourceMetrics[i], true)
}
orig.Reset()
if nullable {
protoPoolExportMetricsServiceRequest.Put(orig)
}
}
func CopyExportMetricsServiceRequest(dest, src *ExportMetricsServiceRequest) *ExportMetricsServiceRequest {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportMetricsServiceRequest()
}
dest.ResourceMetrics = CopyResourceMetricsPtrSlice(dest.ResourceMetrics, src.ResourceMetrics)
return dest
}
func CopyExportMetricsServiceRequestSlice(dest, src []ExportMetricsServiceRequest) []ExportMetricsServiceRequest {
var newDest []ExportMetricsServiceRequest
if cap(dest) < len(src) {
newDest = make([]ExportMetricsServiceRequest, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportMetricsServiceRequest(&dest[i], false)
}
}
for i := range src {
CopyExportMetricsServiceRequest(&newDest[i], &src[i])
}
return newDest
}
func CopyExportMetricsServiceRequestPtrSlice(dest, src []*ExportMetricsServiceRequest) []*ExportMetricsServiceRequest {
var newDest []*ExportMetricsServiceRequest
if cap(dest) < len(src) {
newDest = make([]*ExportMetricsServiceRequest, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportMetricsServiceRequest()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportMetricsServiceRequest(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportMetricsServiceRequest()
}
}
for i := range src {
CopyExportMetricsServiceRequest(newDest[i], src[i])
}
return newDest
}
func (orig *ExportMetricsServiceRequest) Reset() {
*orig = ExportMetricsServiceRequest{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportMetricsServiceRequest) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.ResourceMetrics) > 0 {
dest.WriteObjectField("resourceMetrics")
dest.WriteArrayStart()
orig.ResourceMetrics[0].MarshalJSON(dest)
for i := 1; i < len(orig.ResourceMetrics); i++ {
dest.WriteMore()
orig.ResourceMetrics[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportMetricsServiceRequest) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resourceMetrics", "resource_metrics":
for iter.ReadArray() {
orig.ResourceMetrics = append(orig.ResourceMetrics, NewResourceMetrics())
orig.ResourceMetrics[len(orig.ResourceMetrics)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportMetricsServiceRequest) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.ResourceMetrics {
l = orig.ResourceMetrics[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ExportMetricsServiceRequest) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.ResourceMetrics) - 1; i >= 0; i-- {
l = orig.ResourceMetrics[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *ExportMetricsServiceRequest) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ResourceMetrics", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ResourceMetrics = append(orig.ResourceMetrics, NewResourceMetrics())
err = orig.ResourceMetrics[len(orig.ResourceMetrics)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportMetricsServiceRequest() *ExportMetricsServiceRequest {
orig := NewExportMetricsServiceRequest()
orig.ResourceMetrics = []*ResourceMetrics{{}, GenTestResourceMetrics()}
return orig
}
func GenTestExportMetricsServiceRequestPtrSlice() []*ExportMetricsServiceRequest {
orig := make([]*ExportMetricsServiceRequest, 5)
orig[0] = NewExportMetricsServiceRequest()
orig[1] = GenTestExportMetricsServiceRequest()
orig[2] = NewExportMetricsServiceRequest()
orig[3] = GenTestExportMetricsServiceRequest()
orig[4] = NewExportMetricsServiceRequest()
return orig
}
func GenTestExportMetricsServiceRequestSlice() []ExportMetricsServiceRequest {
orig := make([]ExportMetricsServiceRequest, 5)
orig[1] = *GenTestExportMetricsServiceRequest()
orig[3] = *GenTestExportMetricsServiceRequest()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExportResponse represents the response for gRPC/HTTP client/server.
type ExportMetricsServiceResponse struct {
PartialSuccess ExportMetricsPartialSuccess
}
var (
protoPoolExportMetricsServiceResponse = sync.Pool{
New: func() any {
return &ExportMetricsServiceResponse{}
},
}
)
func NewExportMetricsServiceResponse() *ExportMetricsServiceResponse {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportMetricsServiceResponse{}
}
return protoPoolExportMetricsServiceResponse.Get().(*ExportMetricsServiceResponse)
}
func DeleteExportMetricsServiceResponse(orig *ExportMetricsServiceResponse, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteExportMetricsPartialSuccess(&orig.PartialSuccess, false)
orig.Reset()
if nullable {
protoPoolExportMetricsServiceResponse.Put(orig)
}
}
func CopyExportMetricsServiceResponse(dest, src *ExportMetricsServiceResponse) *ExportMetricsServiceResponse {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportMetricsServiceResponse()
}
CopyExportMetricsPartialSuccess(&dest.PartialSuccess, &src.PartialSuccess)
return dest
}
func CopyExportMetricsServiceResponseSlice(dest, src []ExportMetricsServiceResponse) []ExportMetricsServiceResponse {
var newDest []ExportMetricsServiceResponse
if cap(dest) < len(src) {
newDest = make([]ExportMetricsServiceResponse, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportMetricsServiceResponse(&dest[i], false)
}
}
for i := range src {
CopyExportMetricsServiceResponse(&newDest[i], &src[i])
}
return newDest
}
func CopyExportMetricsServiceResponsePtrSlice(dest, src []*ExportMetricsServiceResponse) []*ExportMetricsServiceResponse {
var newDest []*ExportMetricsServiceResponse
if cap(dest) < len(src) {
newDest = make([]*ExportMetricsServiceResponse, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportMetricsServiceResponse()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportMetricsServiceResponse(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportMetricsServiceResponse()
}
}
for i := range src {
CopyExportMetricsServiceResponse(newDest[i], src[i])
}
return newDest
}
func (orig *ExportMetricsServiceResponse) Reset() {
*orig = ExportMetricsServiceResponse{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportMetricsServiceResponse) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("partialSuccess")
orig.PartialSuccess.MarshalJSON(dest)
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportMetricsServiceResponse) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "partialSuccess", "partial_success":
orig.PartialSuccess.UnmarshalJSON(iter)
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportMetricsServiceResponse) SizeProto() int {
var n int
var l int
_ = l
l = orig.PartialSuccess.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
return n
}
func (orig *ExportMetricsServiceResponse) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.PartialSuccess.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
return len(buf) - pos
}
func (orig *ExportMetricsServiceResponse) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field PartialSuccess", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.PartialSuccess.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportMetricsServiceResponse() *ExportMetricsServiceResponse {
orig := NewExportMetricsServiceResponse()
orig.PartialSuccess = *GenTestExportMetricsPartialSuccess()
return orig
}
func GenTestExportMetricsServiceResponsePtrSlice() []*ExportMetricsServiceResponse {
orig := make([]*ExportMetricsServiceResponse, 5)
orig[0] = NewExportMetricsServiceResponse()
orig[1] = GenTestExportMetricsServiceResponse()
orig[2] = NewExportMetricsServiceResponse()
orig[3] = GenTestExportMetricsServiceResponse()
orig[4] = NewExportMetricsServiceResponse()
return orig
}
func GenTestExportMetricsServiceResponseSlice() []ExportMetricsServiceResponse {
orig := make([]ExportMetricsServiceResponse, 5)
orig[1] = *GenTestExportMetricsServiceResponse()
orig[3] = *GenTestExportMetricsServiceResponse()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExportPartialSuccess represents the details of a partially successful export request.
type ExportProfilesPartialSuccess struct {
ErrorMessage string
RejectedProfiles int64
}
var (
protoPoolExportProfilesPartialSuccess = sync.Pool{
New: func() any {
return &ExportProfilesPartialSuccess{}
},
}
)
func NewExportProfilesPartialSuccess() *ExportProfilesPartialSuccess {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportProfilesPartialSuccess{}
}
return protoPoolExportProfilesPartialSuccess.Get().(*ExportProfilesPartialSuccess)
}
func DeleteExportProfilesPartialSuccess(orig *ExportProfilesPartialSuccess, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolExportProfilesPartialSuccess.Put(orig)
}
}
func CopyExportProfilesPartialSuccess(dest, src *ExportProfilesPartialSuccess) *ExportProfilesPartialSuccess {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportProfilesPartialSuccess()
}
dest.RejectedProfiles = src.RejectedProfiles
dest.ErrorMessage = src.ErrorMessage
return dest
}
func CopyExportProfilesPartialSuccessSlice(dest, src []ExportProfilesPartialSuccess) []ExportProfilesPartialSuccess {
var newDest []ExportProfilesPartialSuccess
if cap(dest) < len(src) {
newDest = make([]ExportProfilesPartialSuccess, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportProfilesPartialSuccess(&dest[i], false)
}
}
for i := range src {
CopyExportProfilesPartialSuccess(&newDest[i], &src[i])
}
return newDest
}
func CopyExportProfilesPartialSuccessPtrSlice(dest, src []*ExportProfilesPartialSuccess) []*ExportProfilesPartialSuccess {
var newDest []*ExportProfilesPartialSuccess
if cap(dest) < len(src) {
newDest = make([]*ExportProfilesPartialSuccess, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportProfilesPartialSuccess()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportProfilesPartialSuccess(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportProfilesPartialSuccess()
}
}
for i := range src {
CopyExportProfilesPartialSuccess(newDest[i], src[i])
}
return newDest
}
func (orig *ExportProfilesPartialSuccess) Reset() {
*orig = ExportProfilesPartialSuccess{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportProfilesPartialSuccess) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.RejectedProfiles != int64(0) {
dest.WriteObjectField("rejectedProfiles")
dest.WriteInt64(orig.RejectedProfiles)
}
if orig.ErrorMessage != "" {
dest.WriteObjectField("errorMessage")
dest.WriteString(orig.ErrorMessage)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportProfilesPartialSuccess) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "rejectedProfiles", "rejected_profiles":
orig.RejectedProfiles = iter.ReadInt64()
case "errorMessage", "error_message":
orig.ErrorMessage = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportProfilesPartialSuccess) SizeProto() int {
var n int
var l int
_ = l
if orig.RejectedProfiles != int64(0) {
n += 1 + proto.Sov(uint64(orig.RejectedProfiles))
}
l = len(orig.ErrorMessage)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ExportProfilesPartialSuccess) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.RejectedProfiles != int64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.RejectedProfiles))
pos--
buf[pos] = 0x8
}
l = len(orig.ErrorMessage)
if l > 0 {
pos -= l
copy(buf[pos:], orig.ErrorMessage)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
return len(buf) - pos
}
func (orig *ExportProfilesPartialSuccess) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field RejectedProfiles", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.RejectedProfiles = int64(num)
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ErrorMessage", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ErrorMessage = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportProfilesPartialSuccess() *ExportProfilesPartialSuccess {
orig := NewExportProfilesPartialSuccess()
orig.RejectedProfiles = int64(13)
orig.ErrorMessage = "test_errormessage"
return orig
}
func GenTestExportProfilesPartialSuccessPtrSlice() []*ExportProfilesPartialSuccess {
orig := make([]*ExportProfilesPartialSuccess, 5)
orig[0] = NewExportProfilesPartialSuccess()
orig[1] = GenTestExportProfilesPartialSuccess()
orig[2] = NewExportProfilesPartialSuccess()
orig[3] = GenTestExportProfilesPartialSuccess()
orig[4] = NewExportProfilesPartialSuccess()
return orig
}
func GenTestExportProfilesPartialSuccessSlice() []ExportProfilesPartialSuccess {
orig := make([]ExportProfilesPartialSuccess, 5)
orig[1] = *GenTestExportProfilesPartialSuccess()
orig[3] = *GenTestExportProfilesPartialSuccess()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Profiles is the top-level struct that is propagated through the profiles pipeline.
// Use NewProfiles to create new instance, zero-initialized instance is not valid for use.
type ExportProfilesServiceRequest struct {
ResourceProfiles []*ResourceProfiles
Dictionary ProfilesDictionary
}
var (
protoPoolExportProfilesServiceRequest = sync.Pool{
New: func() any {
return &ExportProfilesServiceRequest{}
},
}
)
func NewExportProfilesServiceRequest() *ExportProfilesServiceRequest {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportProfilesServiceRequest{}
}
return protoPoolExportProfilesServiceRequest.Get().(*ExportProfilesServiceRequest)
}
func DeleteExportProfilesServiceRequest(orig *ExportProfilesServiceRequest, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.ResourceProfiles {
DeleteResourceProfiles(orig.ResourceProfiles[i], true)
}
DeleteProfilesDictionary(&orig.Dictionary, false)
orig.Reset()
if nullable {
protoPoolExportProfilesServiceRequest.Put(orig)
}
}
func CopyExportProfilesServiceRequest(dest, src *ExportProfilesServiceRequest) *ExportProfilesServiceRequest {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportProfilesServiceRequest()
}
dest.ResourceProfiles = CopyResourceProfilesPtrSlice(dest.ResourceProfiles, src.ResourceProfiles)
CopyProfilesDictionary(&dest.Dictionary, &src.Dictionary)
return dest
}
func CopyExportProfilesServiceRequestSlice(dest, src []ExportProfilesServiceRequest) []ExportProfilesServiceRequest {
var newDest []ExportProfilesServiceRequest
if cap(dest) < len(src) {
newDest = make([]ExportProfilesServiceRequest, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportProfilesServiceRequest(&dest[i], false)
}
}
for i := range src {
CopyExportProfilesServiceRequest(&newDest[i], &src[i])
}
return newDest
}
func CopyExportProfilesServiceRequestPtrSlice(dest, src []*ExportProfilesServiceRequest) []*ExportProfilesServiceRequest {
var newDest []*ExportProfilesServiceRequest
if cap(dest) < len(src) {
newDest = make([]*ExportProfilesServiceRequest, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportProfilesServiceRequest()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportProfilesServiceRequest(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportProfilesServiceRequest()
}
}
for i := range src {
CopyExportProfilesServiceRequest(newDest[i], src[i])
}
return newDest
}
func (orig *ExportProfilesServiceRequest) Reset() {
*orig = ExportProfilesServiceRequest{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportProfilesServiceRequest) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.ResourceProfiles) > 0 {
dest.WriteObjectField("resourceProfiles")
dest.WriteArrayStart()
orig.ResourceProfiles[0].MarshalJSON(dest)
for i := 1; i < len(orig.ResourceProfiles); i++ {
dest.WriteMore()
orig.ResourceProfiles[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectField("dictionary")
orig.Dictionary.MarshalJSON(dest)
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportProfilesServiceRequest) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resourceProfiles", "resource_profiles":
for iter.ReadArray() {
orig.ResourceProfiles = append(orig.ResourceProfiles, NewResourceProfiles())
orig.ResourceProfiles[len(orig.ResourceProfiles)-1].UnmarshalJSON(iter)
}
case "dictionary":
orig.Dictionary.UnmarshalJSON(iter)
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportProfilesServiceRequest) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.ResourceProfiles {
l = orig.ResourceProfiles[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = orig.Dictionary.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
return n
}
func (orig *ExportProfilesServiceRequest) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.ResourceProfiles) - 1; i >= 0; i-- {
l = orig.ResourceProfiles[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
l = orig.Dictionary.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
return len(buf) - pos
}
func (orig *ExportProfilesServiceRequest) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ResourceProfiles", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ResourceProfiles = append(orig.ResourceProfiles, NewResourceProfiles())
err = orig.ResourceProfiles[len(orig.ResourceProfiles)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Dictionary", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Dictionary.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportProfilesServiceRequest() *ExportProfilesServiceRequest {
orig := NewExportProfilesServiceRequest()
orig.ResourceProfiles = []*ResourceProfiles{{}, GenTestResourceProfiles()}
orig.Dictionary = *GenTestProfilesDictionary()
return orig
}
func GenTestExportProfilesServiceRequestPtrSlice() []*ExportProfilesServiceRequest {
orig := make([]*ExportProfilesServiceRequest, 5)
orig[0] = NewExportProfilesServiceRequest()
orig[1] = GenTestExportProfilesServiceRequest()
orig[2] = NewExportProfilesServiceRequest()
orig[3] = GenTestExportProfilesServiceRequest()
orig[4] = NewExportProfilesServiceRequest()
return orig
}
func GenTestExportProfilesServiceRequestSlice() []ExportProfilesServiceRequest {
orig := make([]ExportProfilesServiceRequest, 5)
orig[1] = *GenTestExportProfilesServiceRequest()
orig[3] = *GenTestExportProfilesServiceRequest()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExportResponse represents the response for gRPC/HTTP client/server.
type ExportProfilesServiceResponse struct {
PartialSuccess ExportProfilesPartialSuccess
}
var (
protoPoolExportProfilesServiceResponse = sync.Pool{
New: func() any {
return &ExportProfilesServiceResponse{}
},
}
)
func NewExportProfilesServiceResponse() *ExportProfilesServiceResponse {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportProfilesServiceResponse{}
}
return protoPoolExportProfilesServiceResponse.Get().(*ExportProfilesServiceResponse)
}
func DeleteExportProfilesServiceResponse(orig *ExportProfilesServiceResponse, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteExportProfilesPartialSuccess(&orig.PartialSuccess, false)
orig.Reset()
if nullable {
protoPoolExportProfilesServiceResponse.Put(orig)
}
}
func CopyExportProfilesServiceResponse(dest, src *ExportProfilesServiceResponse) *ExportProfilesServiceResponse {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportProfilesServiceResponse()
}
CopyExportProfilesPartialSuccess(&dest.PartialSuccess, &src.PartialSuccess)
return dest
}
func CopyExportProfilesServiceResponseSlice(dest, src []ExportProfilesServiceResponse) []ExportProfilesServiceResponse {
var newDest []ExportProfilesServiceResponse
if cap(dest) < len(src) {
newDest = make([]ExportProfilesServiceResponse, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportProfilesServiceResponse(&dest[i], false)
}
}
for i := range src {
CopyExportProfilesServiceResponse(&newDest[i], &src[i])
}
return newDest
}
func CopyExportProfilesServiceResponsePtrSlice(dest, src []*ExportProfilesServiceResponse) []*ExportProfilesServiceResponse {
var newDest []*ExportProfilesServiceResponse
if cap(dest) < len(src) {
newDest = make([]*ExportProfilesServiceResponse, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportProfilesServiceResponse()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportProfilesServiceResponse(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportProfilesServiceResponse()
}
}
for i := range src {
CopyExportProfilesServiceResponse(newDest[i], src[i])
}
return newDest
}
func (orig *ExportProfilesServiceResponse) Reset() {
*orig = ExportProfilesServiceResponse{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportProfilesServiceResponse) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("partialSuccess")
orig.PartialSuccess.MarshalJSON(dest)
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportProfilesServiceResponse) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "partialSuccess", "partial_success":
orig.PartialSuccess.UnmarshalJSON(iter)
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportProfilesServiceResponse) SizeProto() int {
var n int
var l int
_ = l
l = orig.PartialSuccess.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
return n
}
func (orig *ExportProfilesServiceResponse) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.PartialSuccess.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
return len(buf) - pos
}
func (orig *ExportProfilesServiceResponse) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field PartialSuccess", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.PartialSuccess.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportProfilesServiceResponse() *ExportProfilesServiceResponse {
orig := NewExportProfilesServiceResponse()
orig.PartialSuccess = *GenTestExportProfilesPartialSuccess()
return orig
}
func GenTestExportProfilesServiceResponsePtrSlice() []*ExportProfilesServiceResponse {
orig := make([]*ExportProfilesServiceResponse, 5)
orig[0] = NewExportProfilesServiceResponse()
orig[1] = GenTestExportProfilesServiceResponse()
orig[2] = NewExportProfilesServiceResponse()
orig[3] = GenTestExportProfilesServiceResponse()
orig[4] = NewExportProfilesServiceResponse()
return orig
}
func GenTestExportProfilesServiceResponseSlice() []ExportProfilesServiceResponse {
orig := make([]ExportProfilesServiceResponse, 5)
orig[1] = *GenTestExportProfilesServiceResponse()
orig[3] = *GenTestExportProfilesServiceResponse()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExportPartialSuccess represents the details of a partially successful export request.
type ExportTracePartialSuccess struct {
ErrorMessage string
RejectedSpans int64
}
var (
protoPoolExportTracePartialSuccess = sync.Pool{
New: func() any {
return &ExportTracePartialSuccess{}
},
}
)
func NewExportTracePartialSuccess() *ExportTracePartialSuccess {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportTracePartialSuccess{}
}
return protoPoolExportTracePartialSuccess.Get().(*ExportTracePartialSuccess)
}
func DeleteExportTracePartialSuccess(orig *ExportTracePartialSuccess, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolExportTracePartialSuccess.Put(orig)
}
}
func CopyExportTracePartialSuccess(dest, src *ExportTracePartialSuccess) *ExportTracePartialSuccess {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportTracePartialSuccess()
}
dest.RejectedSpans = src.RejectedSpans
dest.ErrorMessage = src.ErrorMessage
return dest
}
func CopyExportTracePartialSuccessSlice(dest, src []ExportTracePartialSuccess) []ExportTracePartialSuccess {
var newDest []ExportTracePartialSuccess
if cap(dest) < len(src) {
newDest = make([]ExportTracePartialSuccess, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportTracePartialSuccess(&dest[i], false)
}
}
for i := range src {
CopyExportTracePartialSuccess(&newDest[i], &src[i])
}
return newDest
}
func CopyExportTracePartialSuccessPtrSlice(dest, src []*ExportTracePartialSuccess) []*ExportTracePartialSuccess {
var newDest []*ExportTracePartialSuccess
if cap(dest) < len(src) {
newDest = make([]*ExportTracePartialSuccess, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportTracePartialSuccess()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportTracePartialSuccess(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportTracePartialSuccess()
}
}
for i := range src {
CopyExportTracePartialSuccess(newDest[i], src[i])
}
return newDest
}
func (orig *ExportTracePartialSuccess) Reset() {
*orig = ExportTracePartialSuccess{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportTracePartialSuccess) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.RejectedSpans != int64(0) {
dest.WriteObjectField("rejectedSpans")
dest.WriteInt64(orig.RejectedSpans)
}
if orig.ErrorMessage != "" {
dest.WriteObjectField("errorMessage")
dest.WriteString(orig.ErrorMessage)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportTracePartialSuccess) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "rejectedSpans", "rejected_spans":
orig.RejectedSpans = iter.ReadInt64()
case "errorMessage", "error_message":
orig.ErrorMessage = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportTracePartialSuccess) SizeProto() int {
var n int
var l int
_ = l
if orig.RejectedSpans != int64(0) {
n += 1 + proto.Sov(uint64(orig.RejectedSpans))
}
l = len(orig.ErrorMessage)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ExportTracePartialSuccess) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.RejectedSpans != int64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.RejectedSpans))
pos--
buf[pos] = 0x8
}
l = len(orig.ErrorMessage)
if l > 0 {
pos -= l
copy(buf[pos:], orig.ErrorMessage)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
return len(buf) - pos
}
func (orig *ExportTracePartialSuccess) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field RejectedSpans", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.RejectedSpans = int64(num)
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ErrorMessage", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ErrorMessage = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportTracePartialSuccess() *ExportTracePartialSuccess {
orig := NewExportTracePartialSuccess()
orig.RejectedSpans = int64(13)
orig.ErrorMessage = "test_errormessage"
return orig
}
func GenTestExportTracePartialSuccessPtrSlice() []*ExportTracePartialSuccess {
orig := make([]*ExportTracePartialSuccess, 5)
orig[0] = NewExportTracePartialSuccess()
orig[1] = GenTestExportTracePartialSuccess()
orig[2] = NewExportTracePartialSuccess()
orig[3] = GenTestExportTracePartialSuccess()
orig[4] = NewExportTracePartialSuccess()
return orig
}
func GenTestExportTracePartialSuccessSlice() []ExportTracePartialSuccess {
orig := make([]ExportTracePartialSuccess, 5)
orig[1] = *GenTestExportTracePartialSuccess()
orig[3] = *GenTestExportTracePartialSuccess()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Traces is the top-level struct that is propagated through the traces pipeline.
// Use NewTraces to create new instance, zero-initialized instance is not valid for use.
type ExportTraceServiceRequest struct {
ResourceSpans []*ResourceSpans
}
var (
protoPoolExportTraceServiceRequest = sync.Pool{
New: func() any {
return &ExportTraceServiceRequest{}
},
}
)
func NewExportTraceServiceRequest() *ExportTraceServiceRequest {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportTraceServiceRequest{}
}
return protoPoolExportTraceServiceRequest.Get().(*ExportTraceServiceRequest)
}
func DeleteExportTraceServiceRequest(orig *ExportTraceServiceRequest, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.ResourceSpans {
DeleteResourceSpans(orig.ResourceSpans[i], true)
}
orig.Reset()
if nullable {
protoPoolExportTraceServiceRequest.Put(orig)
}
}
func CopyExportTraceServiceRequest(dest, src *ExportTraceServiceRequest) *ExportTraceServiceRequest {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportTraceServiceRequest()
}
dest.ResourceSpans = CopyResourceSpansPtrSlice(dest.ResourceSpans, src.ResourceSpans)
return dest
}
func CopyExportTraceServiceRequestSlice(dest, src []ExportTraceServiceRequest) []ExportTraceServiceRequest {
var newDest []ExportTraceServiceRequest
if cap(dest) < len(src) {
newDest = make([]ExportTraceServiceRequest, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportTraceServiceRequest(&dest[i], false)
}
}
for i := range src {
CopyExportTraceServiceRequest(&newDest[i], &src[i])
}
return newDest
}
func CopyExportTraceServiceRequestPtrSlice(dest, src []*ExportTraceServiceRequest) []*ExportTraceServiceRequest {
var newDest []*ExportTraceServiceRequest
if cap(dest) < len(src) {
newDest = make([]*ExportTraceServiceRequest, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportTraceServiceRequest()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportTraceServiceRequest(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportTraceServiceRequest()
}
}
for i := range src {
CopyExportTraceServiceRequest(newDest[i], src[i])
}
return newDest
}
func (orig *ExportTraceServiceRequest) Reset() {
*orig = ExportTraceServiceRequest{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportTraceServiceRequest) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.ResourceSpans) > 0 {
dest.WriteObjectField("resourceSpans")
dest.WriteArrayStart()
orig.ResourceSpans[0].MarshalJSON(dest)
for i := 1; i < len(orig.ResourceSpans); i++ {
dest.WriteMore()
orig.ResourceSpans[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportTraceServiceRequest) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resourceSpans", "resource_spans":
for iter.ReadArray() {
orig.ResourceSpans = append(orig.ResourceSpans, NewResourceSpans())
orig.ResourceSpans[len(orig.ResourceSpans)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportTraceServiceRequest) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.ResourceSpans {
l = orig.ResourceSpans[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ExportTraceServiceRequest) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.ResourceSpans) - 1; i >= 0; i-- {
l = orig.ResourceSpans[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *ExportTraceServiceRequest) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ResourceSpans", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ResourceSpans = append(orig.ResourceSpans, NewResourceSpans())
err = orig.ResourceSpans[len(orig.ResourceSpans)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportTraceServiceRequest() *ExportTraceServiceRequest {
orig := NewExportTraceServiceRequest()
orig.ResourceSpans = []*ResourceSpans{{}, GenTestResourceSpans()}
return orig
}
func GenTestExportTraceServiceRequestPtrSlice() []*ExportTraceServiceRequest {
orig := make([]*ExportTraceServiceRequest, 5)
orig[0] = NewExportTraceServiceRequest()
orig[1] = GenTestExportTraceServiceRequest()
orig[2] = NewExportTraceServiceRequest()
orig[3] = GenTestExportTraceServiceRequest()
orig[4] = NewExportTraceServiceRequest()
return orig
}
func GenTestExportTraceServiceRequestSlice() []ExportTraceServiceRequest {
orig := make([]ExportTraceServiceRequest, 5)
orig[1] = *GenTestExportTraceServiceRequest()
orig[3] = *GenTestExportTraceServiceRequest()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ExportResponse represents the response for gRPC/HTTP client/server.
type ExportTraceServiceResponse struct {
PartialSuccess ExportTracePartialSuccess
}
var (
protoPoolExportTraceServiceResponse = sync.Pool{
New: func() any {
return &ExportTraceServiceResponse{}
},
}
)
func NewExportTraceServiceResponse() *ExportTraceServiceResponse {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ExportTraceServiceResponse{}
}
return protoPoolExportTraceServiceResponse.Get().(*ExportTraceServiceResponse)
}
func DeleteExportTraceServiceResponse(orig *ExportTraceServiceResponse, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteExportTracePartialSuccess(&orig.PartialSuccess, false)
orig.Reset()
if nullable {
protoPoolExportTraceServiceResponse.Put(orig)
}
}
func CopyExportTraceServiceResponse(dest, src *ExportTraceServiceResponse) *ExportTraceServiceResponse {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewExportTraceServiceResponse()
}
CopyExportTracePartialSuccess(&dest.PartialSuccess, &src.PartialSuccess)
return dest
}
func CopyExportTraceServiceResponseSlice(dest, src []ExportTraceServiceResponse) []ExportTraceServiceResponse {
var newDest []ExportTraceServiceResponse
if cap(dest) < len(src) {
newDest = make([]ExportTraceServiceResponse, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportTraceServiceResponse(&dest[i], false)
}
}
for i := range src {
CopyExportTraceServiceResponse(&newDest[i], &src[i])
}
return newDest
}
func CopyExportTraceServiceResponsePtrSlice(dest, src []*ExportTraceServiceResponse) []*ExportTraceServiceResponse {
var newDest []*ExportTraceServiceResponse
if cap(dest) < len(src) {
newDest = make([]*ExportTraceServiceResponse, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportTraceServiceResponse()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteExportTraceServiceResponse(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewExportTraceServiceResponse()
}
}
for i := range src {
CopyExportTraceServiceResponse(newDest[i], src[i])
}
return newDest
}
func (orig *ExportTraceServiceResponse) Reset() {
*orig = ExportTraceServiceResponse{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ExportTraceServiceResponse) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("partialSuccess")
orig.PartialSuccess.MarshalJSON(dest)
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ExportTraceServiceResponse) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "partialSuccess", "partial_success":
orig.PartialSuccess.UnmarshalJSON(iter)
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ExportTraceServiceResponse) SizeProto() int {
var n int
var l int
_ = l
l = orig.PartialSuccess.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
return n
}
func (orig *ExportTraceServiceResponse) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.PartialSuccess.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
return len(buf) - pos
}
func (orig *ExportTraceServiceResponse) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field PartialSuccess", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.PartialSuccess.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestExportTraceServiceResponse() *ExportTraceServiceResponse {
orig := NewExportTraceServiceResponse()
orig.PartialSuccess = *GenTestExportTracePartialSuccess()
return orig
}
func GenTestExportTraceServiceResponsePtrSlice() []*ExportTraceServiceResponse {
orig := make([]*ExportTraceServiceResponse, 5)
orig[0] = NewExportTraceServiceResponse()
orig[1] = GenTestExportTraceServiceResponse()
orig[2] = NewExportTraceServiceResponse()
orig[3] = GenTestExportTraceServiceResponse()
orig[4] = NewExportTraceServiceResponse()
return orig
}
func GenTestExportTraceServiceResponseSlice() []ExportTraceServiceResponse {
orig := make([]ExportTraceServiceResponse, 5)
orig[1] = *GenTestExportTraceServiceResponse()
orig[3] = *GenTestExportTraceServiceResponse()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Function describes a function, including its human-readable name, system name, source file, and starting line number in the source.
type Function struct {
NameStrindex int32
SystemNameStrindex int32
FilenameStrindex int32
StartLine int64
}
var (
protoPoolFunction = sync.Pool{
New: func() any {
return &Function{}
},
}
)
func NewFunction() *Function {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Function{}
}
return protoPoolFunction.Get().(*Function)
}
func DeleteFunction(orig *Function, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolFunction.Put(orig)
}
}
func CopyFunction(dest, src *Function) *Function {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewFunction()
}
dest.NameStrindex = src.NameStrindex
dest.SystemNameStrindex = src.SystemNameStrindex
dest.FilenameStrindex = src.FilenameStrindex
dest.StartLine = src.StartLine
return dest
}
func CopyFunctionSlice(dest, src []Function) []Function {
var newDest []Function
if cap(dest) < len(src) {
newDest = make([]Function, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteFunction(&dest[i], false)
}
}
for i := range src {
CopyFunction(&newDest[i], &src[i])
}
return newDest
}
func CopyFunctionPtrSlice(dest, src []*Function) []*Function {
var newDest []*Function
if cap(dest) < len(src) {
newDest = make([]*Function, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewFunction()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteFunction(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewFunction()
}
}
for i := range src {
CopyFunction(newDest[i], src[i])
}
return newDest
}
func (orig *Function) Reset() {
*orig = Function{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Function) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.NameStrindex != int32(0) {
dest.WriteObjectField("nameStrindex")
dest.WriteInt32(orig.NameStrindex)
}
if orig.SystemNameStrindex != int32(0) {
dest.WriteObjectField("systemNameStrindex")
dest.WriteInt32(orig.SystemNameStrindex)
}
if orig.FilenameStrindex != int32(0) {
dest.WriteObjectField("filenameStrindex")
dest.WriteInt32(orig.FilenameStrindex)
}
if orig.StartLine != int64(0) {
dest.WriteObjectField("startLine")
dest.WriteInt64(orig.StartLine)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Function) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "nameStrindex", "name_strindex":
orig.NameStrindex = iter.ReadInt32()
case "systemNameStrindex", "system_name_strindex":
orig.SystemNameStrindex = iter.ReadInt32()
case "filenameStrindex", "filename_strindex":
orig.FilenameStrindex = iter.ReadInt32()
case "startLine", "start_line":
orig.StartLine = iter.ReadInt64()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Function) SizeProto() int {
var n int
var l int
_ = l
if orig.NameStrindex != int32(0) {
n += 1 + proto.Sov(uint64(orig.NameStrindex))
}
if orig.SystemNameStrindex != int32(0) {
n += 1 + proto.Sov(uint64(orig.SystemNameStrindex))
}
if orig.FilenameStrindex != int32(0) {
n += 1 + proto.Sov(uint64(orig.FilenameStrindex))
}
if orig.StartLine != int64(0) {
n += 1 + proto.Sov(uint64(orig.StartLine))
}
return n
}
func (orig *Function) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.NameStrindex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.NameStrindex))
pos--
buf[pos] = 0x8
}
if orig.SystemNameStrindex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.SystemNameStrindex))
pos--
buf[pos] = 0x10
}
if orig.FilenameStrindex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.FilenameStrindex))
pos--
buf[pos] = 0x18
}
if orig.StartLine != int64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.StartLine))
pos--
buf[pos] = 0x20
}
return len(buf) - pos
}
func (orig *Function) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field NameStrindex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.NameStrindex = int32(num)
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field SystemNameStrindex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.SystemNameStrindex = int32(num)
case 3:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field FilenameStrindex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.FilenameStrindex = int32(num)
case 4:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field StartLine", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.StartLine = int64(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestFunction() *Function {
orig := NewFunction()
orig.NameStrindex = int32(13)
orig.SystemNameStrindex = int32(13)
orig.FilenameStrindex = int32(13)
orig.StartLine = int64(13)
return orig
}
func GenTestFunctionPtrSlice() []*Function {
orig := make([]*Function, 5)
orig[0] = NewFunction()
orig[1] = GenTestFunction()
orig[2] = NewFunction()
orig[3] = GenTestFunction()
orig[4] = NewFunction()
return orig
}
func GenTestFunctionSlice() []Function {
orig := make([]Function, 5)
orig[1] = *GenTestFunction()
orig[3] = *GenTestFunction()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Gauge represents the type of a numeric metric that always exports the "current value" for every data point.
type Gauge struct {
DataPoints []*NumberDataPoint
}
var (
protoPoolGauge = sync.Pool{
New: func() any {
return &Gauge{}
},
}
)
func NewGauge() *Gauge {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Gauge{}
}
return protoPoolGauge.Get().(*Gauge)
}
func DeleteGauge(orig *Gauge, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.DataPoints {
DeleteNumberDataPoint(orig.DataPoints[i], true)
}
orig.Reset()
if nullable {
protoPoolGauge.Put(orig)
}
}
func CopyGauge(dest, src *Gauge) *Gauge {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewGauge()
}
dest.DataPoints = CopyNumberDataPointPtrSlice(dest.DataPoints, src.DataPoints)
return dest
}
func CopyGaugeSlice(dest, src []Gauge) []Gauge {
var newDest []Gauge
if cap(dest) < len(src) {
newDest = make([]Gauge, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteGauge(&dest[i], false)
}
}
for i := range src {
CopyGauge(&newDest[i], &src[i])
}
return newDest
}
func CopyGaugePtrSlice(dest, src []*Gauge) []*Gauge {
var newDest []*Gauge
if cap(dest) < len(src) {
newDest = make([]*Gauge, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewGauge()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteGauge(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewGauge()
}
}
for i := range src {
CopyGauge(newDest[i], src[i])
}
return newDest
}
func (orig *Gauge) Reset() {
*orig = Gauge{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Gauge) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.DataPoints) > 0 {
dest.WriteObjectField("dataPoints")
dest.WriteArrayStart()
orig.DataPoints[0].MarshalJSON(dest)
for i := 1; i < len(orig.DataPoints); i++ {
dest.WriteMore()
orig.DataPoints[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Gauge) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "dataPoints", "data_points":
for iter.ReadArray() {
orig.DataPoints = append(orig.DataPoints, NewNumberDataPoint())
orig.DataPoints[len(orig.DataPoints)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Gauge) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.DataPoints {
l = orig.DataPoints[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *Gauge) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.DataPoints) - 1; i >= 0; i-- {
l = orig.DataPoints[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *Gauge) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field DataPoints", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.DataPoints = append(orig.DataPoints, NewNumberDataPoint())
err = orig.DataPoints[len(orig.DataPoints)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestGauge() *Gauge {
orig := NewGauge()
orig.DataPoints = []*NumberDataPoint{{}, GenTestNumberDataPoint()}
return orig
}
func GenTestGaugePtrSlice() []*Gauge {
orig := make([]*Gauge, 5)
orig[0] = NewGauge()
orig[1] = GenTestGauge()
orig[2] = NewGauge()
orig[3] = GenTestGauge()
orig[4] = NewGauge()
return orig
}
func GenTestGaugeSlice() []Gauge {
orig := make([]Gauge, 5)
orig[1] = *GenTestGauge()
orig[3] = *GenTestGauge()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Histogram represents the type of a metric that is calculated by aggregating as a Histogram of all reported measurements over a time interval.
type Histogram struct {
DataPoints []*HistogramDataPoint
AggregationTemporality AggregationTemporality
}
var (
protoPoolHistogram = sync.Pool{
New: func() any {
return &Histogram{}
},
}
)
func NewHistogram() *Histogram {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Histogram{}
}
return protoPoolHistogram.Get().(*Histogram)
}
func DeleteHistogram(orig *Histogram, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.DataPoints {
DeleteHistogramDataPoint(orig.DataPoints[i], true)
}
orig.Reset()
if nullable {
protoPoolHistogram.Put(orig)
}
}
func CopyHistogram(dest, src *Histogram) *Histogram {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewHistogram()
}
dest.DataPoints = CopyHistogramDataPointPtrSlice(dest.DataPoints, src.DataPoints)
dest.AggregationTemporality = src.AggregationTemporality
return dest
}
func CopyHistogramSlice(dest, src []Histogram) []Histogram {
var newDest []Histogram
if cap(dest) < len(src) {
newDest = make([]Histogram, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteHistogram(&dest[i], false)
}
}
for i := range src {
CopyHistogram(&newDest[i], &src[i])
}
return newDest
}
func CopyHistogramPtrSlice(dest, src []*Histogram) []*Histogram {
var newDest []*Histogram
if cap(dest) < len(src) {
newDest = make([]*Histogram, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewHistogram()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteHistogram(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewHistogram()
}
}
for i := range src {
CopyHistogram(newDest[i], src[i])
}
return newDest
}
func (orig *Histogram) Reset() {
*orig = Histogram{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Histogram) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.DataPoints) > 0 {
dest.WriteObjectField("dataPoints")
dest.WriteArrayStart()
orig.DataPoints[0].MarshalJSON(dest)
for i := 1; i < len(orig.DataPoints); i++ {
dest.WriteMore()
orig.DataPoints[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if int32(orig.AggregationTemporality) != 0 {
dest.WriteObjectField("aggregationTemporality")
dest.WriteInt32(int32(orig.AggregationTemporality))
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Histogram) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "dataPoints", "data_points":
for iter.ReadArray() {
orig.DataPoints = append(orig.DataPoints, NewHistogramDataPoint())
orig.DataPoints[len(orig.DataPoints)-1].UnmarshalJSON(iter)
}
case "aggregationTemporality", "aggregation_temporality":
orig.AggregationTemporality = AggregationTemporality(iter.ReadEnumValue(AggregationTemporality_value))
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Histogram) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.DataPoints {
l = orig.DataPoints[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.AggregationTemporality != AggregationTemporality(0) {
n += 1 + proto.Sov(uint64(orig.AggregationTemporality))
}
return n
}
func (orig *Histogram) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.DataPoints) - 1; i >= 0; i-- {
l = orig.DataPoints[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
if orig.AggregationTemporality != AggregationTemporality(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.AggregationTemporality))
pos--
buf[pos] = 0x10
}
return len(buf) - pos
}
func (orig *Histogram) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field DataPoints", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.DataPoints = append(orig.DataPoints, NewHistogramDataPoint())
err = orig.DataPoints[len(orig.DataPoints)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field AggregationTemporality", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.AggregationTemporality = AggregationTemporality(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestHistogram() *Histogram {
orig := NewHistogram()
orig.DataPoints = []*HistogramDataPoint{{}, GenTestHistogramDataPoint()}
orig.AggregationTemporality = AggregationTemporality(13)
return orig
}
func GenTestHistogramPtrSlice() []*Histogram {
orig := make([]*Histogram, 5)
orig[0] = NewHistogram()
orig[1] = GenTestHistogram()
orig[2] = NewHistogram()
orig[3] = GenTestHistogram()
orig[4] = NewHistogram()
return orig
}
func GenTestHistogramSlice() []Histogram {
orig := make([]Histogram, 5)
orig[1] = *GenTestHistogram()
orig[3] = *GenTestHistogram()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"math"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// HistogramDataPoint is a single data point in a timeseries that describes the time-varying values of a Histogram of values.
type HistogramDataPoint struct {
Attributes []KeyValue
BucketCounts []uint64
ExplicitBounds []float64
Exemplars []Exemplar
StartTimeUnixNano uint64
TimeUnixNano uint64
Count uint64
Sum float64
Min float64
Max float64
metadata [1]uint64
Flags uint32
}
var (
protoPoolHistogramDataPoint = sync.Pool{
New: func() any {
return &HistogramDataPoint{}
},
}
)
func NewHistogramDataPoint() *HistogramDataPoint {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &HistogramDataPoint{}
}
return protoPoolHistogramDataPoint.Get().(*HistogramDataPoint)
}
func DeleteHistogramDataPoint(orig *HistogramDataPoint, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.Attributes {
DeleteKeyValue(&orig.Attributes[i], false)
}
for i := range orig.Exemplars {
DeleteExemplar(&orig.Exemplars[i], false)
}
orig.Reset()
if nullable {
protoPoolHistogramDataPoint.Put(orig)
}
}
func CopyHistogramDataPoint(dest, src *HistogramDataPoint) *HistogramDataPoint {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewHistogramDataPoint()
}
dest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)
dest.StartTimeUnixNano = src.StartTimeUnixNano
dest.TimeUnixNano = src.TimeUnixNano
dest.Count = src.Count
if src.HasSum() {
dest.SetSum(src.Sum)
} else {
dest.RemoveSum()
}
dest.BucketCounts = append(dest.BucketCounts[:0], src.BucketCounts...)
dest.ExplicitBounds = append(dest.ExplicitBounds[:0], src.ExplicitBounds...)
dest.Exemplars = CopyExemplarSlice(dest.Exemplars, src.Exemplars)
dest.Flags = src.Flags
if src.HasMin() {
dest.SetMin(src.Min)
} else {
dest.RemoveMin()
}
if src.HasMax() {
dest.SetMax(src.Max)
} else {
dest.RemoveMax()
}
return dest
}
func CopyHistogramDataPointSlice(dest, src []HistogramDataPoint) []HistogramDataPoint {
var newDest []HistogramDataPoint
if cap(dest) < len(src) {
newDest = make([]HistogramDataPoint, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteHistogramDataPoint(&dest[i], false)
}
}
for i := range src {
CopyHistogramDataPoint(&newDest[i], &src[i])
}
return newDest
}
func CopyHistogramDataPointPtrSlice(dest, src []*HistogramDataPoint) []*HistogramDataPoint {
var newDest []*HistogramDataPoint
if cap(dest) < len(src) {
newDest = make([]*HistogramDataPoint, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewHistogramDataPoint()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteHistogramDataPoint(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewHistogramDataPoint()
}
}
for i := range src {
CopyHistogramDataPoint(newDest[i], src[i])
}
return newDest
}
func (orig *HistogramDataPoint) Reset() {
*orig = HistogramDataPoint{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *HistogramDataPoint) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.Attributes) > 0 {
dest.WriteObjectField("attributes")
dest.WriteArrayStart()
orig.Attributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.Attributes); i++ {
dest.WriteMore()
orig.Attributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.StartTimeUnixNano != uint64(0) {
dest.WriteObjectField("startTimeUnixNano")
dest.WriteUint64(orig.StartTimeUnixNano)
}
if orig.TimeUnixNano != uint64(0) {
dest.WriteObjectField("timeUnixNano")
dest.WriteUint64(orig.TimeUnixNano)
}
if orig.Count != uint64(0) {
dest.WriteObjectField("count")
dest.WriteUint64(orig.Count)
}
if orig.HasSum() {
dest.WriteObjectField("sum")
dest.WriteFloat64(orig.Sum)
}
if len(orig.BucketCounts) > 0 {
dest.WriteObjectField("bucketCounts")
dest.WriteArrayStart()
dest.WriteUint64(orig.BucketCounts[0])
for i := 1; i < len(orig.BucketCounts); i++ {
dest.WriteMore()
dest.WriteUint64(orig.BucketCounts[i])
}
dest.WriteArrayEnd()
}
if len(orig.ExplicitBounds) > 0 {
dest.WriteObjectField("explicitBounds")
dest.WriteArrayStart()
dest.WriteFloat64(orig.ExplicitBounds[0])
for i := 1; i < len(orig.ExplicitBounds); i++ {
dest.WriteMore()
dest.WriteFloat64(orig.ExplicitBounds[i])
}
dest.WriteArrayEnd()
}
if len(orig.Exemplars) > 0 {
dest.WriteObjectField("exemplars")
dest.WriteArrayStart()
orig.Exemplars[0].MarshalJSON(dest)
for i := 1; i < len(orig.Exemplars); i++ {
dest.WriteMore()
orig.Exemplars[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.Flags != uint32(0) {
dest.WriteObjectField("flags")
dest.WriteUint32(orig.Flags)
}
if orig.HasMin() {
dest.WriteObjectField("min")
dest.WriteFloat64(orig.Min)
}
if orig.HasMax() {
dest.WriteObjectField("max")
dest.WriteFloat64(orig.Max)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *HistogramDataPoint) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "attributes":
for iter.ReadArray() {
orig.Attributes = append(orig.Attributes, KeyValue{})
orig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)
}
case "startTimeUnixNano", "start_time_unix_nano":
orig.StartTimeUnixNano = iter.ReadUint64()
case "timeUnixNano", "time_unix_nano":
orig.TimeUnixNano = iter.ReadUint64()
case "count":
orig.Count = iter.ReadUint64()
case "sum":
orig.SetSum(iter.ReadFloat64())
case "bucketCounts", "bucket_counts":
for iter.ReadArray() {
orig.BucketCounts = append(orig.BucketCounts, iter.ReadUint64())
}
case "explicitBounds", "explicit_bounds":
for iter.ReadArray() {
orig.ExplicitBounds = append(orig.ExplicitBounds, iter.ReadFloat64())
}
case "exemplars":
for iter.ReadArray() {
orig.Exemplars = append(orig.Exemplars, Exemplar{})
orig.Exemplars[len(orig.Exemplars)-1].UnmarshalJSON(iter)
}
case "flags":
orig.Flags = iter.ReadUint32()
case "min":
orig.SetMin(iter.ReadFloat64())
case "max":
orig.SetMax(iter.ReadFloat64())
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *HistogramDataPoint) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.Attributes {
l = orig.Attributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.StartTimeUnixNano != uint64(0) {
n += 9
}
if orig.TimeUnixNano != uint64(0) {
n += 9
}
if orig.Count != uint64(0) {
n += 9
}
if orig.HasSum() {
n += 9
}
l = len(orig.BucketCounts)
if l > 0 {
l *= 8
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.ExplicitBounds)
if l > 0 {
l *= 8
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.Exemplars {
l = orig.Exemplars[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.Flags != uint32(0) {
n += 1 + proto.Sov(uint64(orig.Flags))
}
if orig.HasMin() {
n += 9
}
if orig.HasMax() {
n += 9
}
return n
}
func (orig *HistogramDataPoint) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.Attributes) - 1; i >= 0; i-- {
l = orig.Attributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x4a
}
if orig.StartTimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.StartTimeUnixNano))
pos--
buf[pos] = 0x11
}
if orig.TimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))
pos--
buf[pos] = 0x19
}
if orig.Count != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.Count))
pos--
buf[pos] = 0x21
}
if orig.HasSum() {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Sum))
pos--
buf[pos] = 0x29
}
l = len(orig.BucketCounts)
if l > 0 {
for i := l - 1; i >= 0; i-- {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.BucketCounts[i]))
}
pos = proto.EncodeVarint(buf, pos, uint64(l*8))
pos--
buf[pos] = 0x32
}
l = len(orig.ExplicitBounds)
if l > 0 {
for i := l - 1; i >= 0; i-- {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.ExplicitBounds[i]))
}
pos = proto.EncodeVarint(buf, pos, uint64(l*8))
pos--
buf[pos] = 0x3a
}
for i := len(orig.Exemplars) - 1; i >= 0; i-- {
l = orig.Exemplars[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x42
}
if orig.Flags != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Flags))
pos--
buf[pos] = 0x50
}
if orig.HasMin() {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Min))
pos--
buf[pos] = 0x59
}
if orig.HasMax() {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Max))
pos--
buf[pos] = 0x61
}
return len(buf) - pos
}
func (orig *HistogramDataPoint) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 9:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Attributes = append(orig.Attributes, KeyValue{})
err = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field StartTimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.StartTimeUnixNano = uint64(num)
case 3:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field TimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.TimeUnixNano = uint64(num)
case 4:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Count", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.Count = uint64(num)
case 5:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Sum", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.SetSum(math.Float64frombits(num))
case 6:
switch wireType {
case proto.WireTypeLen:
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
size := length / 8
orig.BucketCounts = make([]uint64, size)
var num uint64
for i := 0; i < size; i++ {
num, startPos, err = proto.ConsumeI64(buf[:pos], startPos)
if err != nil {
return err
}
orig.BucketCounts[i] = uint64(num)
}
if startPos != pos {
return fmt.Errorf("proto: invalid field len = %d for field BucketCounts", pos-startPos)
}
case proto.WireTypeI64:
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.BucketCounts = append(orig.BucketCounts, uint64(num))
default:
return fmt.Errorf("proto: wrong wireType = %d for field BucketCounts", wireType)
}
case 7:
switch wireType {
case proto.WireTypeLen:
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
size := length / 8
orig.ExplicitBounds = make([]float64, size)
var num uint64
for i := 0; i < size; i++ {
num, startPos, err = proto.ConsumeI64(buf[:pos], startPos)
if err != nil {
return err
}
orig.ExplicitBounds[i] = math.Float64frombits(num)
}
if startPos != pos {
return fmt.Errorf("proto: invalid field len = %d for field ExplicitBounds", pos-startPos)
}
case proto.WireTypeI64:
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.ExplicitBounds = append(orig.ExplicitBounds, math.Float64frombits(num))
default:
return fmt.Errorf("proto: wrong wireType = %d for field ExplicitBounds", wireType)
}
case 8:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Exemplars", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Exemplars = append(orig.Exemplars, Exemplar{})
err = orig.Exemplars[len(orig.Exemplars)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 10:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Flags", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Flags = uint32(num)
case 11:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Min", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.SetMin(math.Float64frombits(num))
case 12:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Max", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.SetMax(math.Float64frombits(num))
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
const fieldBlockHistogramDataPointSum = uint64(0 >> 6)
const fieldBitHistogramDataPointSum = uint64(1 << 0 & 0x3F)
func (m *HistogramDataPoint) SetSum(value float64) {
m.Sum = value
m.metadata[fieldBlockHistogramDataPointSum] |= fieldBitHistogramDataPointSum
}
func (m *HistogramDataPoint) RemoveSum() {
m.Sum = float64(0)
m.metadata[fieldBlockHistogramDataPointSum] &^= fieldBitHistogramDataPointSum
}
func (m *HistogramDataPoint) HasSum() bool {
return m.metadata[fieldBlockHistogramDataPointSum]&fieldBitHistogramDataPointSum != 0
}
const fieldBlockHistogramDataPointMin = uint64(1 >> 6)
const fieldBitHistogramDataPointMin = uint64(1 << 1 & 0x3F)
func (m *HistogramDataPoint) SetMin(value float64) {
m.Min = value
m.metadata[fieldBlockHistogramDataPointMin] |= fieldBitHistogramDataPointMin
}
func (m *HistogramDataPoint) RemoveMin() {
m.Min = float64(0)
m.metadata[fieldBlockHistogramDataPointMin] &^= fieldBitHistogramDataPointMin
}
func (m *HistogramDataPoint) HasMin() bool {
return m.metadata[fieldBlockHistogramDataPointMin]&fieldBitHistogramDataPointMin != 0
}
const fieldBlockHistogramDataPointMax = uint64(2 >> 6)
const fieldBitHistogramDataPointMax = uint64(1 << 2 & 0x3F)
func (m *HistogramDataPoint) SetMax(value float64) {
m.Max = value
m.metadata[fieldBlockHistogramDataPointMax] |= fieldBitHistogramDataPointMax
}
func (m *HistogramDataPoint) RemoveMax() {
m.Max = float64(0)
m.metadata[fieldBlockHistogramDataPointMax] &^= fieldBitHistogramDataPointMax
}
func (m *HistogramDataPoint) HasMax() bool {
return m.metadata[fieldBlockHistogramDataPointMax]&fieldBitHistogramDataPointMax != 0
}
func GenTestHistogramDataPoint() *HistogramDataPoint {
orig := NewHistogramDataPoint()
orig.Attributes = []KeyValue{{}, *GenTestKeyValue()}
orig.StartTimeUnixNano = uint64(13)
orig.TimeUnixNano = uint64(13)
orig.Count = uint64(13)
orig.SetSum(float64(3.1415926))
orig.BucketCounts = []uint64{uint64(0), uint64(13)}
orig.ExplicitBounds = []float64{float64(0), float64(3.1415926)}
orig.Exemplars = []Exemplar{{}, *GenTestExemplar()}
orig.Flags = uint32(13)
orig.SetMin(float64(3.1415926))
orig.SetMax(float64(3.1415926))
return orig
}
func GenTestHistogramDataPointPtrSlice() []*HistogramDataPoint {
orig := make([]*HistogramDataPoint, 5)
orig[0] = NewHistogramDataPoint()
orig[1] = GenTestHistogramDataPoint()
orig[2] = NewHistogramDataPoint()
orig[3] = GenTestHistogramDataPoint()
orig[4] = NewHistogramDataPoint()
return orig
}
func GenTestHistogramDataPointSlice() []HistogramDataPoint {
orig := make([]HistogramDataPoint, 5)
orig[1] = *GenTestHistogramDataPoint()
orig[3] = *GenTestHistogramDataPoint()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// InstrumentationScope is a message representing the instrumentation scope information.
type InstrumentationScope struct {
Name string
Version string
Attributes []KeyValue
DroppedAttributesCount uint32
}
var (
protoPoolInstrumentationScope = sync.Pool{
New: func() any {
return &InstrumentationScope{}
},
}
)
func NewInstrumentationScope() *InstrumentationScope {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &InstrumentationScope{}
}
return protoPoolInstrumentationScope.Get().(*InstrumentationScope)
}
func DeleteInstrumentationScope(orig *InstrumentationScope, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.Attributes {
DeleteKeyValue(&orig.Attributes[i], false)
}
orig.Reset()
if nullable {
protoPoolInstrumentationScope.Put(orig)
}
}
func CopyInstrumentationScope(dest, src *InstrumentationScope) *InstrumentationScope {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewInstrumentationScope()
}
dest.Name = src.Name
dest.Version = src.Version
dest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)
dest.DroppedAttributesCount = src.DroppedAttributesCount
return dest
}
func CopyInstrumentationScopeSlice(dest, src []InstrumentationScope) []InstrumentationScope {
var newDest []InstrumentationScope
if cap(dest) < len(src) {
newDest = make([]InstrumentationScope, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteInstrumentationScope(&dest[i], false)
}
}
for i := range src {
CopyInstrumentationScope(&newDest[i], &src[i])
}
return newDest
}
func CopyInstrumentationScopePtrSlice(dest, src []*InstrumentationScope) []*InstrumentationScope {
var newDest []*InstrumentationScope
if cap(dest) < len(src) {
newDest = make([]*InstrumentationScope, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewInstrumentationScope()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteInstrumentationScope(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewInstrumentationScope()
}
}
for i := range src {
CopyInstrumentationScope(newDest[i], src[i])
}
return newDest
}
func (orig *InstrumentationScope) Reset() {
*orig = InstrumentationScope{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *InstrumentationScope) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.Name != "" {
dest.WriteObjectField("name")
dest.WriteString(orig.Name)
}
if orig.Version != "" {
dest.WriteObjectField("version")
dest.WriteString(orig.Version)
}
if len(orig.Attributes) > 0 {
dest.WriteObjectField("attributes")
dest.WriteArrayStart()
orig.Attributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.Attributes); i++ {
dest.WriteMore()
orig.Attributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.DroppedAttributesCount != uint32(0) {
dest.WriteObjectField("droppedAttributesCount")
dest.WriteUint32(orig.DroppedAttributesCount)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *InstrumentationScope) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "name":
orig.Name = iter.ReadString()
case "version":
orig.Version = iter.ReadString()
case "attributes":
for iter.ReadArray() {
orig.Attributes = append(orig.Attributes, KeyValue{})
orig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)
}
case "droppedAttributesCount", "dropped_attributes_count":
orig.DroppedAttributesCount = iter.ReadUint32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *InstrumentationScope) SizeProto() int {
var n int
var l int
_ = l
l = len(orig.Name)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.Version)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.Attributes {
l = orig.Attributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.DroppedAttributesCount != uint32(0) {
n += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))
}
return n
}
func (orig *InstrumentationScope) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = len(orig.Name)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Name)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
l = len(orig.Version)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Version)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
for i := len(orig.Attributes) - 1; i >= 0; i-- {
l = orig.Attributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
if orig.DroppedAttributesCount != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))
pos--
buf[pos] = 0x20
}
return len(buf) - pos
}
func (orig *InstrumentationScope) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Name = string(buf[startPos:pos])
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Version = string(buf[startPos:pos])
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Attributes = append(orig.Attributes, KeyValue{})
err = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 4:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field DroppedAttributesCount", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.DroppedAttributesCount = uint32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestInstrumentationScope() *InstrumentationScope {
orig := NewInstrumentationScope()
orig.Name = "test_name"
orig.Version = "test_version"
orig.Attributes = []KeyValue{{}, *GenTestKeyValue()}
orig.DroppedAttributesCount = uint32(13)
return orig
}
func GenTestInstrumentationScopePtrSlice() []*InstrumentationScope {
orig := make([]*InstrumentationScope, 5)
orig[0] = NewInstrumentationScope()
orig[1] = GenTestInstrumentationScope()
orig[2] = NewInstrumentationScope()
orig[3] = GenTestInstrumentationScope()
orig[4] = NewInstrumentationScope()
return orig
}
func GenTestInstrumentationScopeSlice() []InstrumentationScope {
orig := make([]InstrumentationScope, 5)
orig[1] = *GenTestInstrumentationScope()
orig[3] = *GenTestInstrumentationScope()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type IPAddr struct {
Zone string
IP []byte
}
var (
protoPoolIPAddr = sync.Pool{
New: func() any {
return &IPAddr{}
},
}
)
func NewIPAddr() *IPAddr {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &IPAddr{}
}
return protoPoolIPAddr.Get().(*IPAddr)
}
func DeleteIPAddr(orig *IPAddr, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolIPAddr.Put(orig)
}
}
func CopyIPAddr(dest, src *IPAddr) *IPAddr {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewIPAddr()
}
dest.IP = src.IP
dest.Zone = src.Zone
return dest
}
func CopyIPAddrSlice(dest, src []IPAddr) []IPAddr {
var newDest []IPAddr
if cap(dest) < len(src) {
newDest = make([]IPAddr, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteIPAddr(&dest[i], false)
}
}
for i := range src {
CopyIPAddr(&newDest[i], &src[i])
}
return newDest
}
func CopyIPAddrPtrSlice(dest, src []*IPAddr) []*IPAddr {
var newDest []*IPAddr
if cap(dest) < len(src) {
newDest = make([]*IPAddr, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewIPAddr()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteIPAddr(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewIPAddr()
}
}
for i := range src {
CopyIPAddr(newDest[i], src[i])
}
return newDest
}
func (orig *IPAddr) Reset() {
*orig = IPAddr{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *IPAddr) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.IP) > 0 {
dest.WriteObjectField("iP")
dest.WriteBytes(orig.IP)
}
if orig.Zone != "" {
dest.WriteObjectField("zone")
dest.WriteString(orig.Zone)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *IPAddr) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "iP":
orig.IP = iter.ReadBytes()
case "zone":
orig.Zone = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *IPAddr) SizeProto() int {
var n int
var l int
_ = l
l = len(orig.IP)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.Zone)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *IPAddr) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = len(orig.IP)
if l > 0 {
pos -= l
copy(buf[pos:], orig.IP)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
l = len(orig.Zone)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Zone)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
return len(buf) - pos
}
func (orig *IPAddr) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field IP", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
if length != 0 {
orig.IP = make([]byte, length)
copy(orig.IP, buf[startPos:pos])
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Zone", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Zone = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestIPAddr() *IPAddr {
orig := NewIPAddr()
orig.IP = []byte{1, 2, 3}
orig.Zone = "test_zone"
return orig
}
func GenTestIPAddrPtrSlice() []*IPAddr {
orig := make([]*IPAddr, 5)
orig[0] = NewIPAddr()
orig[1] = GenTestIPAddr()
orig[2] = NewIPAddr()
orig[3] = GenTestIPAddr()
orig[4] = NewIPAddr()
return orig
}
func GenTestIPAddrSlice() []IPAddr {
orig := make([]IPAddr, 5)
orig[1] = *GenTestIPAddr()
orig[3] = *GenTestIPAddr()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type KeyValue struct {
Value AnyValue
Key string
KeyStrindex int32
}
var (
protoPoolKeyValue = sync.Pool{
New: func() any {
return &KeyValue{}
},
}
)
func NewKeyValue() *KeyValue {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &KeyValue{}
}
return protoPoolKeyValue.Get().(*KeyValue)
}
func DeleteKeyValue(orig *KeyValue, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteAnyValue(&orig.Value, false)
orig.Reset()
if nullable {
protoPoolKeyValue.Put(orig)
}
}
func CopyKeyValue(dest, src *KeyValue) *KeyValue {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewKeyValue()
}
dest.Key = src.Key
CopyAnyValue(&dest.Value, &src.Value)
dest.KeyStrindex = src.KeyStrindex
return dest
}
func CopyKeyValueSlice(dest, src []KeyValue) []KeyValue {
var newDest []KeyValue
if cap(dest) < len(src) {
newDest = make([]KeyValue, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteKeyValue(&dest[i], false)
}
}
for i := range src {
CopyKeyValue(&newDest[i], &src[i])
}
return newDest
}
func CopyKeyValuePtrSlice(dest, src []*KeyValue) []*KeyValue {
var newDest []*KeyValue
if cap(dest) < len(src) {
newDest = make([]*KeyValue, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewKeyValue()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteKeyValue(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewKeyValue()
}
}
for i := range src {
CopyKeyValue(newDest[i], src[i])
}
return newDest
}
func (orig *KeyValue) Reset() {
*orig = KeyValue{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *KeyValue) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.Key != "" {
dest.WriteObjectField("key")
dest.WriteString(orig.Key)
}
dest.WriteObjectField("value")
orig.Value.MarshalJSON(dest)
if orig.KeyStrindex != int32(0) {
dest.WriteObjectField("keyStrindex")
dest.WriteInt32(orig.KeyStrindex)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *KeyValue) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "key":
orig.Key = iter.ReadString()
case "value":
orig.Value.UnmarshalJSON(iter)
case "keyStrindex", "key_strindex":
orig.KeyStrindex = iter.ReadInt32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *KeyValue) SizeProto() int {
var n int
var l int
_ = l
l = len(orig.Key)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
l = orig.Value.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.KeyStrindex != int32(0) {
n += 1 + proto.Sov(uint64(orig.KeyStrindex))
}
return n
}
func (orig *KeyValue) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = len(orig.Key)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Key)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
l = orig.Value.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
if orig.KeyStrindex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.KeyStrindex))
pos--
buf[pos] = 0x18
}
return len(buf) - pos
}
func (orig *KeyValue) UnmarshalProto(buf []byte) error {
return orig.unmarshalProto(buf, 0)
}
func (orig *KeyValue) unmarshalProto(buf []byte, depth int) error {
if depth >= proto.RecursionLimit {
return proto.ErrRecursionDepth
}
depth++
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Key = string(buf[startPos:pos])
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Value.unmarshalProto(buf[startPos:pos], depth)
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field KeyStrindex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.KeyStrindex = int32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestKeyValue() *KeyValue {
orig := NewKeyValue()
orig.Key = "test_key"
orig.Value = *GenTestAnyValue()
orig.KeyStrindex = int32(13)
return orig
}
func GenTestKeyValuePtrSlice() []*KeyValue {
orig := make([]*KeyValue, 5)
orig[0] = NewKeyValue()
orig[1] = GenTestKeyValue()
orig[2] = NewKeyValue()
orig[3] = GenTestKeyValue()
orig[4] = NewKeyValue()
return orig
}
func GenTestKeyValueSlice() []KeyValue {
orig := make([]KeyValue, 5)
orig[1] = *GenTestKeyValue()
orig[3] = *GenTestKeyValue()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// KeyValueAndUnit represents a custom 'dictionary native'
// style of encoding attributes which is more convenient
// for profiles than opentelemetry.proto.common.v1.KeyValue.
type KeyValueAndUnit struct {
Value AnyValue
KeyStrindex int32
UnitStrindex int32
}
var (
protoPoolKeyValueAndUnit = sync.Pool{
New: func() any {
return &KeyValueAndUnit{}
},
}
)
func NewKeyValueAndUnit() *KeyValueAndUnit {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &KeyValueAndUnit{}
}
return protoPoolKeyValueAndUnit.Get().(*KeyValueAndUnit)
}
func DeleteKeyValueAndUnit(orig *KeyValueAndUnit, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteAnyValue(&orig.Value, false)
orig.Reset()
if nullable {
protoPoolKeyValueAndUnit.Put(orig)
}
}
func CopyKeyValueAndUnit(dest, src *KeyValueAndUnit) *KeyValueAndUnit {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewKeyValueAndUnit()
}
dest.KeyStrindex = src.KeyStrindex
CopyAnyValue(&dest.Value, &src.Value)
dest.UnitStrindex = src.UnitStrindex
return dest
}
func CopyKeyValueAndUnitSlice(dest, src []KeyValueAndUnit) []KeyValueAndUnit {
var newDest []KeyValueAndUnit
if cap(dest) < len(src) {
newDest = make([]KeyValueAndUnit, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteKeyValueAndUnit(&dest[i], false)
}
}
for i := range src {
CopyKeyValueAndUnit(&newDest[i], &src[i])
}
return newDest
}
func CopyKeyValueAndUnitPtrSlice(dest, src []*KeyValueAndUnit) []*KeyValueAndUnit {
var newDest []*KeyValueAndUnit
if cap(dest) < len(src) {
newDest = make([]*KeyValueAndUnit, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewKeyValueAndUnit()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteKeyValueAndUnit(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewKeyValueAndUnit()
}
}
for i := range src {
CopyKeyValueAndUnit(newDest[i], src[i])
}
return newDest
}
func (orig *KeyValueAndUnit) Reset() {
*orig = KeyValueAndUnit{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *KeyValueAndUnit) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.KeyStrindex != int32(0) {
dest.WriteObjectField("keyStrindex")
dest.WriteInt32(orig.KeyStrindex)
}
dest.WriteObjectField("value")
orig.Value.MarshalJSON(dest)
if orig.UnitStrindex != int32(0) {
dest.WriteObjectField("unitStrindex")
dest.WriteInt32(orig.UnitStrindex)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *KeyValueAndUnit) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "keyStrindex", "key_strindex":
orig.KeyStrindex = iter.ReadInt32()
case "value":
orig.Value.UnmarshalJSON(iter)
case "unitStrindex", "unit_strindex":
orig.UnitStrindex = iter.ReadInt32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *KeyValueAndUnit) SizeProto() int {
var n int
var l int
_ = l
if orig.KeyStrindex != int32(0) {
n += 1 + proto.Sov(uint64(orig.KeyStrindex))
}
l = orig.Value.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.UnitStrindex != int32(0) {
n += 1 + proto.Sov(uint64(orig.UnitStrindex))
}
return n
}
func (orig *KeyValueAndUnit) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.KeyStrindex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.KeyStrindex))
pos--
buf[pos] = 0x8
}
l = orig.Value.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
if orig.UnitStrindex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.UnitStrindex))
pos--
buf[pos] = 0x18
}
return len(buf) - pos
}
func (orig *KeyValueAndUnit) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field KeyStrindex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.KeyStrindex = int32(num)
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Value.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field UnitStrindex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.UnitStrindex = int32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestKeyValueAndUnit() *KeyValueAndUnit {
orig := NewKeyValueAndUnit()
orig.KeyStrindex = int32(13)
orig.Value = *GenTestAnyValue()
orig.UnitStrindex = int32(13)
return orig
}
func GenTestKeyValueAndUnitPtrSlice() []*KeyValueAndUnit {
orig := make([]*KeyValueAndUnit, 5)
orig[0] = NewKeyValueAndUnit()
orig[1] = GenTestKeyValueAndUnit()
orig[2] = NewKeyValueAndUnit()
orig[3] = GenTestKeyValueAndUnit()
orig[4] = NewKeyValueAndUnit()
return orig
}
func GenTestKeyValueAndUnitSlice() []KeyValueAndUnit {
orig := make([]KeyValueAndUnit, 5)
orig[1] = *GenTestKeyValueAndUnit()
orig[3] = *GenTestKeyValueAndUnit()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// KeyValueList is a list of KeyValue messages. We need KeyValueList as a message since oneof in AnyValue does not allow repeated fields.
type KeyValueList struct {
Values []KeyValue
}
var (
protoPoolKeyValueList = sync.Pool{
New: func() any {
return &KeyValueList{}
},
}
)
func NewKeyValueList() *KeyValueList {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &KeyValueList{}
}
return protoPoolKeyValueList.Get().(*KeyValueList)
}
func DeleteKeyValueList(orig *KeyValueList, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.Values {
DeleteKeyValue(&orig.Values[i], false)
}
orig.Reset()
if nullable {
protoPoolKeyValueList.Put(orig)
}
}
func CopyKeyValueList(dest, src *KeyValueList) *KeyValueList {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewKeyValueList()
}
dest.Values = CopyKeyValueSlice(dest.Values, src.Values)
return dest
}
func CopyKeyValueListSlice(dest, src []KeyValueList) []KeyValueList {
var newDest []KeyValueList
if cap(dest) < len(src) {
newDest = make([]KeyValueList, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteKeyValueList(&dest[i], false)
}
}
for i := range src {
CopyKeyValueList(&newDest[i], &src[i])
}
return newDest
}
func CopyKeyValueListPtrSlice(dest, src []*KeyValueList) []*KeyValueList {
var newDest []*KeyValueList
if cap(dest) < len(src) {
newDest = make([]*KeyValueList, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewKeyValueList()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteKeyValueList(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewKeyValueList()
}
}
for i := range src {
CopyKeyValueList(newDest[i], src[i])
}
return newDest
}
func (orig *KeyValueList) Reset() {
*orig = KeyValueList{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *KeyValueList) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.Values) > 0 {
dest.WriteObjectField("values")
dest.WriteArrayStart()
orig.Values[0].MarshalJSON(dest)
for i := 1; i < len(orig.Values); i++ {
dest.WriteMore()
orig.Values[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *KeyValueList) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "values":
for iter.ReadArray() {
orig.Values = append(orig.Values, KeyValue{})
orig.Values[len(orig.Values)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *KeyValueList) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.Values {
l = orig.Values[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *KeyValueList) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.Values) - 1; i >= 0; i-- {
l = orig.Values[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *KeyValueList) UnmarshalProto(buf []byte) error {
return orig.unmarshalProto(buf, 0)
}
func (orig *KeyValueList) unmarshalProto(buf []byte, depth int) error {
if depth >= proto.RecursionLimit {
return proto.ErrRecursionDepth
}
depth++
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Values", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Values = append(orig.Values, KeyValue{})
err = orig.Values[len(orig.Values)-1].unmarshalProto(buf[startPos:pos], depth)
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestKeyValueList() *KeyValueList {
orig := NewKeyValueList()
orig.Values = []KeyValue{{}, *GenTestKeyValue()}
return orig
}
func GenTestKeyValueListPtrSlice() []*KeyValueList {
orig := make([]*KeyValueList, 5)
orig[0] = NewKeyValueList()
orig[1] = GenTestKeyValueList()
orig[2] = NewKeyValueList()
orig[3] = GenTestKeyValueList()
orig[4] = NewKeyValueList()
return orig
}
func GenTestKeyValueListSlice() []KeyValueList {
orig := make([]KeyValueList, 5)
orig[1] = *GenTestKeyValueList()
orig[3] = *GenTestKeyValueList()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Line details a specific line in a source code, linked to a function.
type Line struct {
FunctionIndex int32
Line int64
Column int64
}
var (
protoPoolLine = sync.Pool{
New: func() any {
return &Line{}
},
}
)
func NewLine() *Line {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Line{}
}
return protoPoolLine.Get().(*Line)
}
func DeleteLine(orig *Line, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolLine.Put(orig)
}
}
func CopyLine(dest, src *Line) *Line {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewLine()
}
dest.FunctionIndex = src.FunctionIndex
dest.Line = src.Line
dest.Column = src.Column
return dest
}
func CopyLineSlice(dest, src []Line) []Line {
var newDest []Line
if cap(dest) < len(src) {
newDest = make([]Line, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLine(&dest[i], false)
}
}
for i := range src {
CopyLine(&newDest[i], &src[i])
}
return newDest
}
func CopyLinePtrSlice(dest, src []*Line) []*Line {
var newDest []*Line
if cap(dest) < len(src) {
newDest = make([]*Line, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLine()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLine(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLine()
}
}
for i := range src {
CopyLine(newDest[i], src[i])
}
return newDest
}
func (orig *Line) Reset() {
*orig = Line{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Line) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.FunctionIndex != int32(0) {
dest.WriteObjectField("functionIndex")
dest.WriteInt32(orig.FunctionIndex)
}
if orig.Line != int64(0) {
dest.WriteObjectField("line")
dest.WriteInt64(orig.Line)
}
if orig.Column != int64(0) {
dest.WriteObjectField("column")
dest.WriteInt64(orig.Column)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Line) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "functionIndex", "function_index":
orig.FunctionIndex = iter.ReadInt32()
case "line":
orig.Line = iter.ReadInt64()
case "column":
orig.Column = iter.ReadInt64()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Line) SizeProto() int {
var n int
var l int
_ = l
if orig.FunctionIndex != int32(0) {
n += 1 + proto.Sov(uint64(orig.FunctionIndex))
}
if orig.Line != int64(0) {
n += 1 + proto.Sov(uint64(orig.Line))
}
if orig.Column != int64(0) {
n += 1 + proto.Sov(uint64(orig.Column))
}
return n
}
func (orig *Line) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.FunctionIndex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.FunctionIndex))
pos--
buf[pos] = 0x8
}
if orig.Line != int64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Line))
pos--
buf[pos] = 0x10
}
if orig.Column != int64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Column))
pos--
buf[pos] = 0x18
}
return len(buf) - pos
}
func (orig *Line) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field FunctionIndex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.FunctionIndex = int32(num)
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Line", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Line = int64(num)
case 3:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Column", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Column = int64(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestLine() *Line {
orig := NewLine()
orig.FunctionIndex = int32(13)
orig.Line = int64(13)
orig.Column = int64(13)
return orig
}
func GenTestLinePtrSlice() []*Line {
orig := make([]*Line, 5)
orig[0] = NewLine()
orig[1] = GenTestLine()
orig[2] = NewLine()
orig[3] = GenTestLine()
orig[4] = NewLine()
return orig
}
func GenTestLineSlice() []Line {
orig := make([]Line, 5)
orig[1] = *GenTestLine()
orig[3] = *GenTestLine()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Link represents a pointer from a profile Sample to a trace Span.
type Link struct {
TraceId TraceID
SpanId SpanID
}
var (
protoPoolLink = sync.Pool{
New: func() any {
return &Link{}
},
}
)
func NewLink() *Link {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Link{}
}
return protoPoolLink.Get().(*Link)
}
func DeleteLink(orig *Link, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteTraceID(&orig.TraceId, false)
DeleteSpanID(&orig.SpanId, false)
orig.Reset()
if nullable {
protoPoolLink.Put(orig)
}
}
func CopyLink(dest, src *Link) *Link {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewLink()
}
CopyTraceID(&dest.TraceId, &src.TraceId)
CopySpanID(&dest.SpanId, &src.SpanId)
return dest
}
func CopyLinkSlice(dest, src []Link) []Link {
var newDest []Link
if cap(dest) < len(src) {
newDest = make([]Link, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLink(&dest[i], false)
}
}
for i := range src {
CopyLink(&newDest[i], &src[i])
}
return newDest
}
func CopyLinkPtrSlice(dest, src []*Link) []*Link {
var newDest []*Link
if cap(dest) < len(src) {
newDest = make([]*Link, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLink()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLink(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLink()
}
}
for i := range src {
CopyLink(newDest[i], src[i])
}
return newDest
}
func (orig *Link) Reset() {
*orig = Link{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Link) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if !orig.TraceId.IsEmpty() {
dest.WriteObjectField("traceId")
orig.TraceId.MarshalJSON(dest)
}
if !orig.SpanId.IsEmpty() {
dest.WriteObjectField("spanId")
orig.SpanId.MarshalJSON(dest)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Link) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "traceId", "trace_id":
orig.TraceId.UnmarshalJSON(iter)
case "spanId", "span_id":
orig.SpanId.UnmarshalJSON(iter)
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Link) SizeProto() int {
var n int
var l int
_ = l
l = orig.TraceId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
l = orig.SpanId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
return n
}
func (orig *Link) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.TraceId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
l = orig.SpanId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
return len(buf) - pos
}
func (orig *Link) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TraceId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.TraceId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SpanId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.SpanId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestLink() *Link {
orig := NewLink()
orig.TraceId = *GenTestTraceID()
orig.SpanId = *GenTestSpanID()
return orig
}
func GenTestLinkPtrSlice() []*Link {
orig := make([]*Link, 5)
orig[0] = NewLink()
orig[1] = GenTestLink()
orig[2] = NewLink()
orig[3] = GenTestLink()
orig[4] = NewLink()
return orig
}
func GenTestLinkSlice() []Link {
orig := make([]Link, 5)
orig[1] = *GenTestLink()
orig[3] = *GenTestLink()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Location describes function and line table debug information.
type Location struct {
Lines []*Line
AttributeIndices []int32
Address uint64
MappingIndex int32
}
var (
protoPoolLocation = sync.Pool{
New: func() any {
return &Location{}
},
}
)
func NewLocation() *Location {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Location{}
}
return protoPoolLocation.Get().(*Location)
}
func DeleteLocation(orig *Location, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.Lines {
DeleteLine(orig.Lines[i], true)
}
orig.Reset()
if nullable {
protoPoolLocation.Put(orig)
}
}
func CopyLocation(dest, src *Location) *Location {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewLocation()
}
dest.MappingIndex = src.MappingIndex
dest.Address = src.Address
dest.Lines = CopyLinePtrSlice(dest.Lines, src.Lines)
dest.AttributeIndices = append(dest.AttributeIndices[:0], src.AttributeIndices...)
return dest
}
func CopyLocationSlice(dest, src []Location) []Location {
var newDest []Location
if cap(dest) < len(src) {
newDest = make([]Location, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLocation(&dest[i], false)
}
}
for i := range src {
CopyLocation(&newDest[i], &src[i])
}
return newDest
}
func CopyLocationPtrSlice(dest, src []*Location) []*Location {
var newDest []*Location
if cap(dest) < len(src) {
newDest = make([]*Location, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLocation()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLocation(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLocation()
}
}
for i := range src {
CopyLocation(newDest[i], src[i])
}
return newDest
}
func (orig *Location) Reset() {
*orig = Location{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Location) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.MappingIndex != int32(0) {
dest.WriteObjectField("mappingIndex")
dest.WriteInt32(orig.MappingIndex)
}
if orig.Address != uint64(0) {
dest.WriteObjectField("address")
dest.WriteUint64(orig.Address)
}
if len(orig.Lines) > 0 {
dest.WriteObjectField("lines")
dest.WriteArrayStart()
orig.Lines[0].MarshalJSON(dest)
for i := 1; i < len(orig.Lines); i++ {
dest.WriteMore()
orig.Lines[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if len(orig.AttributeIndices) > 0 {
dest.WriteObjectField("attributeIndices")
dest.WriteArrayStart()
dest.WriteInt32(orig.AttributeIndices[0])
for i := 1; i < len(orig.AttributeIndices); i++ {
dest.WriteMore()
dest.WriteInt32(orig.AttributeIndices[i])
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Location) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "mappingIndex", "mapping_index":
orig.MappingIndex = iter.ReadInt32()
case "address":
orig.Address = iter.ReadUint64()
case "lines":
for iter.ReadArray() {
orig.Lines = append(orig.Lines, NewLine())
orig.Lines[len(orig.Lines)-1].UnmarshalJSON(iter)
}
case "attributeIndices", "attribute_indices":
for iter.ReadArray() {
orig.AttributeIndices = append(orig.AttributeIndices, iter.ReadInt32())
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Location) SizeProto() int {
var n int
var l int
_ = l
if orig.MappingIndex != int32(0) {
n += 1 + proto.Sov(uint64(orig.MappingIndex))
}
if orig.Address != uint64(0) {
n += 1 + proto.Sov(uint64(orig.Address))
}
for i := range orig.Lines {
l = orig.Lines[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if len(orig.AttributeIndices) > 0 {
l = 0
for _, e := range orig.AttributeIndices {
l += proto.Sov(uint64(e))
}
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *Location) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.MappingIndex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.MappingIndex))
pos--
buf[pos] = 0x8
}
if orig.Address != uint64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Address))
pos--
buf[pos] = 0x10
}
for i := len(orig.Lines) - 1; i >= 0; i-- {
l = orig.Lines[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
l = len(orig.AttributeIndices)
if l > 0 {
endPos := pos
for i := l - 1; i >= 0; i-- {
pos = proto.EncodeVarint(buf, pos, uint64(orig.AttributeIndices[i]))
}
pos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))
pos--
buf[pos] = 0x22
}
return len(buf) - pos
}
func (orig *Location) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field MappingIndex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.MappingIndex = int32(num)
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Address = uint64(num)
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Lines", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Lines = append(orig.Lines, NewLine())
err = orig.Lines[len(orig.Lines)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 4:
switch wireType {
case proto.WireTypeLen:
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
var num uint64
for startPos < pos {
num, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)
if err != nil {
return err
}
orig.AttributeIndices = append(orig.AttributeIndices, int32(num))
}
if startPos != pos {
return fmt.Errorf("proto: invalid field len = %d for field AttributeIndices", pos-startPos)
}
case proto.WireTypeVarint:
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.AttributeIndices = append(orig.AttributeIndices, int32(num))
default:
return fmt.Errorf("proto: wrong wireType = %d for field AttributeIndices", wireType)
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestLocation() *Location {
orig := NewLocation()
orig.MappingIndex = int32(13)
orig.Address = uint64(13)
orig.Lines = []*Line{{}, GenTestLine()}
orig.AttributeIndices = []int32{int32(0), int32(13)}
return orig
}
func GenTestLocationPtrSlice() []*Location {
orig := make([]*Location, 5)
orig[0] = NewLocation()
orig[1] = GenTestLocation()
orig[2] = NewLocation()
orig[3] = GenTestLocation()
orig[4] = NewLocation()
return orig
}
func GenTestLocationSlice() []Location {
orig := make([]Location, 5)
orig[1] = *GenTestLocation()
orig[3] = *GenTestLocation()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// LogRecord are experimental implementation of OpenTelemetry Log Data Model.
type LogRecord struct {
Body AnyValue
SeverityText string
EventName string
Attributes []KeyValue
TimeUnixNano uint64
ObservedTimeUnixNano uint64
SeverityNumber SeverityNumber
DroppedAttributesCount uint32
Flags uint32
TraceId TraceID
SpanId SpanID
}
var (
protoPoolLogRecord = sync.Pool{
New: func() any {
return &LogRecord{}
},
}
)
func NewLogRecord() *LogRecord {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &LogRecord{}
}
return protoPoolLogRecord.Get().(*LogRecord)
}
func DeleteLogRecord(orig *LogRecord, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteAnyValue(&orig.Body, false)
for i := range orig.Attributes {
DeleteKeyValue(&orig.Attributes[i], false)
}
DeleteTraceID(&orig.TraceId, false)
DeleteSpanID(&orig.SpanId, false)
orig.Reset()
if nullable {
protoPoolLogRecord.Put(orig)
}
}
func CopyLogRecord(dest, src *LogRecord) *LogRecord {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewLogRecord()
}
dest.TimeUnixNano = src.TimeUnixNano
dest.ObservedTimeUnixNano = src.ObservedTimeUnixNano
dest.SeverityNumber = src.SeverityNumber
dest.SeverityText = src.SeverityText
CopyAnyValue(&dest.Body, &src.Body)
dest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)
dest.DroppedAttributesCount = src.DroppedAttributesCount
dest.Flags = src.Flags
CopyTraceID(&dest.TraceId, &src.TraceId)
CopySpanID(&dest.SpanId, &src.SpanId)
dest.EventName = src.EventName
return dest
}
func CopyLogRecordSlice(dest, src []LogRecord) []LogRecord {
var newDest []LogRecord
if cap(dest) < len(src) {
newDest = make([]LogRecord, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLogRecord(&dest[i], false)
}
}
for i := range src {
CopyLogRecord(&newDest[i], &src[i])
}
return newDest
}
func CopyLogRecordPtrSlice(dest, src []*LogRecord) []*LogRecord {
var newDest []*LogRecord
if cap(dest) < len(src) {
newDest = make([]*LogRecord, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLogRecord()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLogRecord(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLogRecord()
}
}
for i := range src {
CopyLogRecord(newDest[i], src[i])
}
return newDest
}
func (orig *LogRecord) Reset() {
*orig = LogRecord{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *LogRecord) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.TimeUnixNano != uint64(0) {
dest.WriteObjectField("timeUnixNano")
dest.WriteUint64(orig.TimeUnixNano)
}
if orig.ObservedTimeUnixNano != uint64(0) {
dest.WriteObjectField("observedTimeUnixNano")
dest.WriteUint64(orig.ObservedTimeUnixNano)
}
if int32(orig.SeverityNumber) != 0 {
dest.WriteObjectField("severityNumber")
dest.WriteInt32(int32(orig.SeverityNumber))
}
if orig.SeverityText != "" {
dest.WriteObjectField("severityText")
dest.WriteString(orig.SeverityText)
}
dest.WriteObjectField("body")
orig.Body.MarshalJSON(dest)
if len(orig.Attributes) > 0 {
dest.WriteObjectField("attributes")
dest.WriteArrayStart()
orig.Attributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.Attributes); i++ {
dest.WriteMore()
orig.Attributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.DroppedAttributesCount != uint32(0) {
dest.WriteObjectField("droppedAttributesCount")
dest.WriteUint32(orig.DroppedAttributesCount)
}
if orig.Flags != uint32(0) {
dest.WriteObjectField("flags")
dest.WriteUint32(orig.Flags)
}
if !orig.TraceId.IsEmpty() {
dest.WriteObjectField("traceId")
orig.TraceId.MarshalJSON(dest)
}
if !orig.SpanId.IsEmpty() {
dest.WriteObjectField("spanId")
orig.SpanId.MarshalJSON(dest)
}
if orig.EventName != "" {
dest.WriteObjectField("eventName")
dest.WriteString(orig.EventName)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *LogRecord) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "timeUnixNano", "time_unix_nano":
orig.TimeUnixNano = iter.ReadUint64()
case "observedTimeUnixNano", "observed_time_unix_nano":
orig.ObservedTimeUnixNano = iter.ReadUint64()
case "severityNumber", "severity_number":
orig.SeverityNumber = SeverityNumber(iter.ReadEnumValue(SeverityNumber_value))
case "severityText", "severity_text":
orig.SeverityText = iter.ReadString()
case "body":
orig.Body.UnmarshalJSON(iter)
case "attributes":
for iter.ReadArray() {
orig.Attributes = append(orig.Attributes, KeyValue{})
orig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)
}
case "droppedAttributesCount", "dropped_attributes_count":
orig.DroppedAttributesCount = iter.ReadUint32()
case "flags":
orig.Flags = iter.ReadUint32()
case "traceId", "trace_id":
orig.TraceId.UnmarshalJSON(iter)
case "spanId", "span_id":
orig.SpanId.UnmarshalJSON(iter)
case "eventName", "event_name":
orig.EventName = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *LogRecord) SizeProto() int {
var n int
var l int
_ = l
if orig.TimeUnixNano != uint64(0) {
n += 9
}
if orig.ObservedTimeUnixNano != uint64(0) {
n += 9
}
if orig.SeverityNumber != SeverityNumber(0) {
n += 1 + proto.Sov(uint64(orig.SeverityNumber))
}
l = len(orig.SeverityText)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
l = orig.Body.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
for i := range orig.Attributes {
l = orig.Attributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.DroppedAttributesCount != uint32(0) {
n += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))
}
if orig.Flags != uint32(0) {
n += 5
}
l = orig.TraceId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
l = orig.SpanId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
l = len(orig.EventName)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *LogRecord) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.TimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))
pos--
buf[pos] = 0x9
}
if orig.ObservedTimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.ObservedTimeUnixNano))
pos--
buf[pos] = 0x59
}
if orig.SeverityNumber != SeverityNumber(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.SeverityNumber))
pos--
buf[pos] = 0x10
}
l = len(orig.SeverityText)
if l > 0 {
pos -= l
copy(buf[pos:], orig.SeverityText)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
l = orig.Body.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x2a
for i := len(orig.Attributes) - 1; i >= 0; i-- {
l = orig.Attributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x32
}
if orig.DroppedAttributesCount != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))
pos--
buf[pos] = 0x38
}
if orig.Flags != uint32(0) {
pos -= 4
binary.LittleEndian.PutUint32(buf[pos:], uint32(orig.Flags))
pos--
buf[pos] = 0x45
}
l = orig.TraceId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x4a
l = orig.SpanId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x52
l = len(orig.EventName)
if l > 0 {
pos -= l
copy(buf[pos:], orig.EventName)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x62
}
return len(buf) - pos
}
func (orig *LogRecord) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field TimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.TimeUnixNano = uint64(num)
case 11:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field ObservedTimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.ObservedTimeUnixNano = uint64(num)
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field SeverityNumber", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.SeverityNumber = SeverityNumber(num)
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SeverityText", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SeverityText = string(buf[startPos:pos])
case 5:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Body", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Body.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 6:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Attributes = append(orig.Attributes, KeyValue{})
err = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 7:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field DroppedAttributesCount", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.DroppedAttributesCount = uint32(num)
case 8:
if wireType != proto.WireTypeI32 {
return fmt.Errorf("proto: wrong wireType = %d for field Flags", wireType)
}
var num uint32
num, pos, err = proto.ConsumeI32(buf, pos)
if err != nil {
return err
}
orig.Flags = uint32(num)
case 9:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TraceId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.TraceId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 10:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SpanId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.SpanId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 12:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field EventName", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.EventName = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestLogRecord() *LogRecord {
orig := NewLogRecord()
orig.TimeUnixNano = uint64(13)
orig.ObservedTimeUnixNano = uint64(13)
orig.SeverityNumber = SeverityNumber(13)
orig.SeverityText = "test_severitytext"
orig.Body = *GenTestAnyValue()
orig.Attributes = []KeyValue{{}, *GenTestKeyValue()}
orig.DroppedAttributesCount = uint32(13)
orig.Flags = uint32(13)
orig.TraceId = *GenTestTraceID()
orig.SpanId = *GenTestSpanID()
orig.EventName = "test_eventname"
return orig
}
func GenTestLogRecordPtrSlice() []*LogRecord {
orig := make([]*LogRecord, 5)
orig[0] = NewLogRecord()
orig[1] = GenTestLogRecord()
orig[2] = NewLogRecord()
orig[3] = GenTestLogRecord()
orig[4] = NewLogRecord()
return orig
}
func GenTestLogRecordSlice() []LogRecord {
orig := make([]LogRecord, 5)
orig[1] = *GenTestLogRecord()
orig[3] = *GenTestLogRecord()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// LogsData represents the logs data that can be stored in a persistent storage,
// OR can be embedded by other protocols that transfer OTLP logs data but do not
// implement the OTLP protocol.
type LogsData struct {
ResourceLogs []*ResourceLogs
}
var (
protoPoolLogsData = sync.Pool{
New: func() any {
return &LogsData{}
},
}
)
func NewLogsData() *LogsData {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &LogsData{}
}
return protoPoolLogsData.Get().(*LogsData)
}
func DeleteLogsData(orig *LogsData, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.ResourceLogs {
DeleteResourceLogs(orig.ResourceLogs[i], true)
}
orig.Reset()
if nullable {
protoPoolLogsData.Put(orig)
}
}
func CopyLogsData(dest, src *LogsData) *LogsData {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewLogsData()
}
dest.ResourceLogs = CopyResourceLogsPtrSlice(dest.ResourceLogs, src.ResourceLogs)
return dest
}
func CopyLogsDataSlice(dest, src []LogsData) []LogsData {
var newDest []LogsData
if cap(dest) < len(src) {
newDest = make([]LogsData, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLogsData(&dest[i], false)
}
}
for i := range src {
CopyLogsData(&newDest[i], &src[i])
}
return newDest
}
func CopyLogsDataPtrSlice(dest, src []*LogsData) []*LogsData {
var newDest []*LogsData
if cap(dest) < len(src) {
newDest = make([]*LogsData, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLogsData()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLogsData(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLogsData()
}
}
for i := range src {
CopyLogsData(newDest[i], src[i])
}
return newDest
}
func (orig *LogsData) Reset() {
*orig = LogsData{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *LogsData) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.ResourceLogs) > 0 {
dest.WriteObjectField("resourceLogs")
dest.WriteArrayStart()
orig.ResourceLogs[0].MarshalJSON(dest)
for i := 1; i < len(orig.ResourceLogs); i++ {
dest.WriteMore()
orig.ResourceLogs[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *LogsData) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resourceLogs", "resource_logs":
for iter.ReadArray() {
orig.ResourceLogs = append(orig.ResourceLogs, NewResourceLogs())
orig.ResourceLogs[len(orig.ResourceLogs)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *LogsData) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.ResourceLogs {
l = orig.ResourceLogs[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *LogsData) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.ResourceLogs) - 1; i >= 0; i-- {
l = orig.ResourceLogs[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *LogsData) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ResourceLogs", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ResourceLogs = append(orig.ResourceLogs, NewResourceLogs())
err = orig.ResourceLogs[len(orig.ResourceLogs)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestLogsData() *LogsData {
orig := NewLogsData()
orig.ResourceLogs = []*ResourceLogs{{}, GenTestResourceLogs()}
return orig
}
func GenTestLogsDataPtrSlice() []*LogsData {
orig := make([]*LogsData, 5)
orig[0] = NewLogsData()
orig[1] = GenTestLogsData()
orig[2] = NewLogsData()
orig[3] = GenTestLogsData()
orig[4] = NewLogsData()
return orig
}
func GenTestLogsDataSlice() []LogsData {
orig := make([]LogsData, 5)
orig[1] = *GenTestLogsData()
orig[3] = *GenTestLogsData()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type LogsRequest struct {
RequestContext *RequestContext
LogsData LogsData
FormatVersion uint32
}
var (
protoPoolLogsRequest = sync.Pool{
New: func() any {
return &LogsRequest{}
},
}
)
func NewLogsRequest() *LogsRequest {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &LogsRequest{}
}
return protoPoolLogsRequest.Get().(*LogsRequest)
}
func DeleteLogsRequest(orig *LogsRequest, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteRequestContext(orig.RequestContext, true)
DeleteLogsData(&orig.LogsData, false)
orig.Reset()
if nullable {
protoPoolLogsRequest.Put(orig)
}
}
func CopyLogsRequest(dest, src *LogsRequest) *LogsRequest {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewLogsRequest()
}
dest.RequestContext = CopyRequestContext(dest.RequestContext, src.RequestContext)
CopyLogsData(&dest.LogsData, &src.LogsData)
dest.FormatVersion = src.FormatVersion
return dest
}
func CopyLogsRequestSlice(dest, src []LogsRequest) []LogsRequest {
var newDest []LogsRequest
if cap(dest) < len(src) {
newDest = make([]LogsRequest, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLogsRequest(&dest[i], false)
}
}
for i := range src {
CopyLogsRequest(&newDest[i], &src[i])
}
return newDest
}
func CopyLogsRequestPtrSlice(dest, src []*LogsRequest) []*LogsRequest {
var newDest []*LogsRequest
if cap(dest) < len(src) {
newDest = make([]*LogsRequest, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLogsRequest()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteLogsRequest(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewLogsRequest()
}
}
for i := range src {
CopyLogsRequest(newDest[i], src[i])
}
return newDest
}
func (orig *LogsRequest) Reset() {
*orig = LogsRequest{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *LogsRequest) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.RequestContext != nil {
dest.WriteObjectField("requestContext")
orig.RequestContext.MarshalJSON(dest)
}
dest.WriteObjectField("logsData")
orig.LogsData.MarshalJSON(dest)
if orig.FormatVersion != uint32(0) {
dest.WriteObjectField("formatVersion")
dest.WriteUint32(orig.FormatVersion)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *LogsRequest) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "requestContext", "request_context":
orig.RequestContext = NewRequestContext()
orig.RequestContext.UnmarshalJSON(iter)
case "logsData", "logs_data":
orig.LogsData.UnmarshalJSON(iter)
case "formatVersion", "format_version":
orig.FormatVersion = iter.ReadUint32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *LogsRequest) SizeProto() int {
var n int
var l int
_ = l
if orig.RequestContext != nil {
l = orig.RequestContext.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = orig.LogsData.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.FormatVersion != uint32(0) {
n += 5
}
return n
}
func (orig *LogsRequest) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.RequestContext != nil {
l = orig.RequestContext.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = orig.LogsData.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
if orig.FormatVersion != uint32(0) {
pos -= 4
binary.LittleEndian.PutUint32(buf[pos:], uint32(orig.FormatVersion))
pos--
buf[pos] = 0xd
}
return len(buf) - pos
}
func (orig *LogsRequest) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field RequestContext", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.RequestContext = NewRequestContext()
err = orig.RequestContext.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field LogsData", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.LogsData.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 1:
if wireType != proto.WireTypeI32 {
return fmt.Errorf("proto: wrong wireType = %d for field FormatVersion", wireType)
}
var num uint32
num, pos, err = proto.ConsumeI32(buf, pos)
if err != nil {
return err
}
orig.FormatVersion = uint32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestLogsRequest() *LogsRequest {
orig := NewLogsRequest()
orig.RequestContext = GenTestRequestContext()
orig.LogsData = *GenTestLogsData()
orig.FormatVersion = uint32(13)
return orig
}
func GenTestLogsRequestPtrSlice() []*LogsRequest {
orig := make([]*LogsRequest, 5)
orig[0] = NewLogsRequest()
orig[1] = GenTestLogsRequest()
orig[2] = NewLogsRequest()
orig[3] = GenTestLogsRequest()
orig[4] = NewLogsRequest()
return orig
}
func GenTestLogsRequestSlice() []LogsRequest {
orig := make([]LogsRequest, 5)
orig[1] = *GenTestLogsRequest()
orig[3] = *GenTestLogsRequest()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Mapping describes the mapping of a binary in memory, including its address range, file offset, and metadata like build ID
type Mapping struct {
AttributeIndices []int32
MemoryStart uint64
MemoryLimit uint64
FileOffset uint64
FilenameStrindex int32
}
var (
protoPoolMapping = sync.Pool{
New: func() any {
return &Mapping{}
},
}
)
func NewMapping() *Mapping {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Mapping{}
}
return protoPoolMapping.Get().(*Mapping)
}
func DeleteMapping(orig *Mapping, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolMapping.Put(orig)
}
}
func CopyMapping(dest, src *Mapping) *Mapping {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewMapping()
}
dest.MemoryStart = src.MemoryStart
dest.MemoryLimit = src.MemoryLimit
dest.FileOffset = src.FileOffset
dest.FilenameStrindex = src.FilenameStrindex
dest.AttributeIndices = append(dest.AttributeIndices[:0], src.AttributeIndices...)
return dest
}
func CopyMappingSlice(dest, src []Mapping) []Mapping {
var newDest []Mapping
if cap(dest) < len(src) {
newDest = make([]Mapping, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteMapping(&dest[i], false)
}
}
for i := range src {
CopyMapping(&newDest[i], &src[i])
}
return newDest
}
func CopyMappingPtrSlice(dest, src []*Mapping) []*Mapping {
var newDest []*Mapping
if cap(dest) < len(src) {
newDest = make([]*Mapping, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewMapping()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteMapping(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewMapping()
}
}
for i := range src {
CopyMapping(newDest[i], src[i])
}
return newDest
}
func (orig *Mapping) Reset() {
*orig = Mapping{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Mapping) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.MemoryStart != uint64(0) {
dest.WriteObjectField("memoryStart")
dest.WriteUint64(orig.MemoryStart)
}
if orig.MemoryLimit != uint64(0) {
dest.WriteObjectField("memoryLimit")
dest.WriteUint64(orig.MemoryLimit)
}
if orig.FileOffset != uint64(0) {
dest.WriteObjectField("fileOffset")
dest.WriteUint64(orig.FileOffset)
}
if orig.FilenameStrindex != int32(0) {
dest.WriteObjectField("filenameStrindex")
dest.WriteInt32(orig.FilenameStrindex)
}
if len(orig.AttributeIndices) > 0 {
dest.WriteObjectField("attributeIndices")
dest.WriteArrayStart()
dest.WriteInt32(orig.AttributeIndices[0])
for i := 1; i < len(orig.AttributeIndices); i++ {
dest.WriteMore()
dest.WriteInt32(orig.AttributeIndices[i])
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Mapping) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "memoryStart", "memory_start":
orig.MemoryStart = iter.ReadUint64()
case "memoryLimit", "memory_limit":
orig.MemoryLimit = iter.ReadUint64()
case "fileOffset", "file_offset":
orig.FileOffset = iter.ReadUint64()
case "filenameStrindex", "filename_strindex":
orig.FilenameStrindex = iter.ReadInt32()
case "attributeIndices", "attribute_indices":
for iter.ReadArray() {
orig.AttributeIndices = append(orig.AttributeIndices, iter.ReadInt32())
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Mapping) SizeProto() int {
var n int
var l int
_ = l
if orig.MemoryStart != uint64(0) {
n += 1 + proto.Sov(uint64(orig.MemoryStart))
}
if orig.MemoryLimit != uint64(0) {
n += 1 + proto.Sov(uint64(orig.MemoryLimit))
}
if orig.FileOffset != uint64(0) {
n += 1 + proto.Sov(uint64(orig.FileOffset))
}
if orig.FilenameStrindex != int32(0) {
n += 1 + proto.Sov(uint64(orig.FilenameStrindex))
}
if len(orig.AttributeIndices) > 0 {
l = 0
for _, e := range orig.AttributeIndices {
l += proto.Sov(uint64(e))
}
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *Mapping) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.MemoryStart != uint64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.MemoryStart))
pos--
buf[pos] = 0x8
}
if orig.MemoryLimit != uint64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.MemoryLimit))
pos--
buf[pos] = 0x10
}
if orig.FileOffset != uint64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.FileOffset))
pos--
buf[pos] = 0x18
}
if orig.FilenameStrindex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.FilenameStrindex))
pos--
buf[pos] = 0x20
}
l = len(orig.AttributeIndices)
if l > 0 {
endPos := pos
for i := l - 1; i >= 0; i-- {
pos = proto.EncodeVarint(buf, pos, uint64(orig.AttributeIndices[i]))
}
pos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))
pos--
buf[pos] = 0x2a
}
return len(buf) - pos
}
func (orig *Mapping) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field MemoryStart", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.MemoryStart = uint64(num)
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field MemoryLimit", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.MemoryLimit = uint64(num)
case 3:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field FileOffset", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.FileOffset = uint64(num)
case 4:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field FilenameStrindex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.FilenameStrindex = int32(num)
case 5:
switch wireType {
case proto.WireTypeLen:
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
var num uint64
for startPos < pos {
num, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)
if err != nil {
return err
}
orig.AttributeIndices = append(orig.AttributeIndices, int32(num))
}
if startPos != pos {
return fmt.Errorf("proto: invalid field len = %d for field AttributeIndices", pos-startPos)
}
case proto.WireTypeVarint:
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.AttributeIndices = append(orig.AttributeIndices, int32(num))
default:
return fmt.Errorf("proto: wrong wireType = %d for field AttributeIndices", wireType)
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestMapping() *Mapping {
orig := NewMapping()
orig.MemoryStart = uint64(13)
orig.MemoryLimit = uint64(13)
orig.FileOffset = uint64(13)
orig.FilenameStrindex = int32(13)
orig.AttributeIndices = []int32{int32(0), int32(13)}
return orig
}
func GenTestMappingPtrSlice() []*Mapping {
orig := make([]*Mapping, 5)
orig[0] = NewMapping()
orig[1] = GenTestMapping()
orig[2] = NewMapping()
orig[3] = GenTestMapping()
orig[4] = NewMapping()
return orig
}
func GenTestMappingSlice() []Mapping {
orig := make([]Mapping, 5)
orig[1] = *GenTestMapping()
orig[3] = *GenTestMapping()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
func (m *Metric) GetData() any {
if m != nil {
return m.Data
}
return nil
}
func (m *Metric) deleteData() {
if m == nil {
return
}
switch ov := m.Data.(type) {
case *Metric_Gauge:
deleteMetric_Gauge(ov)
case *Metric_Sum:
deleteMetric_Sum(ov)
case *Metric_Histogram:
deleteMetric_Histogram(ov)
case *Metric_ExponentialHistogram:
deleteMetric_ExponentialHistogram(ov)
case *Metric_Summary:
deleteMetric_Summary(ov)
}
m.Data = nil
}
var (
protoPoolMetric_Gauge = sync.Pool{
New: func() any {
return &Metric_Gauge{}
},
}
)
type Metric_Gauge struct {
Gauge *Gauge
}
func NewMetric_Gauge() *Metric_Gauge {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Metric_Gauge{}
}
return protoPoolMetric_Gauge.Get().(*Metric_Gauge)
}
func deleteMetric_Gauge(v *Metric_Gauge) {
// Called only when pool is enabled
v.Gauge = nil
protoPoolMetric_Gauge.Put(v)
}
func (m *Metric) GetGauge() *Gauge {
if v, ok := m.GetData().(*Metric_Gauge); ok {
return v.Gauge
}
return nil
}
var (
protoPoolMetric_Sum = sync.Pool{
New: func() any {
return &Metric_Sum{}
},
}
)
type Metric_Sum struct {
Sum *Sum
}
func NewMetric_Sum() *Metric_Sum {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Metric_Sum{}
}
return protoPoolMetric_Sum.Get().(*Metric_Sum)
}
func deleteMetric_Sum(v *Metric_Sum) {
// Called only when pool is enabled
v.Sum = nil
protoPoolMetric_Sum.Put(v)
}
func (m *Metric) GetSum() *Sum {
if v, ok := m.GetData().(*Metric_Sum); ok {
return v.Sum
}
return nil
}
var (
protoPoolMetric_Histogram = sync.Pool{
New: func() any {
return &Metric_Histogram{}
},
}
)
type Metric_Histogram struct {
Histogram *Histogram
}
func NewMetric_Histogram() *Metric_Histogram {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Metric_Histogram{}
}
return protoPoolMetric_Histogram.Get().(*Metric_Histogram)
}
func deleteMetric_Histogram(v *Metric_Histogram) {
// Called only when pool is enabled
v.Histogram = nil
protoPoolMetric_Histogram.Put(v)
}
func (m *Metric) GetHistogram() *Histogram {
if v, ok := m.GetData().(*Metric_Histogram); ok {
return v.Histogram
}
return nil
}
var (
protoPoolMetric_ExponentialHistogram = sync.Pool{
New: func() any {
return &Metric_ExponentialHistogram{}
},
}
)
type Metric_ExponentialHistogram struct {
ExponentialHistogram *ExponentialHistogram
}
func NewMetric_ExponentialHistogram() *Metric_ExponentialHistogram {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Metric_ExponentialHistogram{}
}
return protoPoolMetric_ExponentialHistogram.Get().(*Metric_ExponentialHistogram)
}
func deleteMetric_ExponentialHistogram(v *Metric_ExponentialHistogram) {
// Called only when pool is enabled
v.ExponentialHistogram = nil
protoPoolMetric_ExponentialHistogram.Put(v)
}
func (m *Metric) GetExponentialHistogram() *ExponentialHistogram {
if v, ok := m.GetData().(*Metric_ExponentialHistogram); ok {
return v.ExponentialHistogram
}
return nil
}
var (
protoPoolMetric_Summary = sync.Pool{
New: func() any {
return &Metric_Summary{}
},
}
)
type Metric_Summary struct {
Summary *Summary
}
func NewMetric_Summary() *Metric_Summary {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Metric_Summary{}
}
return protoPoolMetric_Summary.Get().(*Metric_Summary)
}
func deleteMetric_Summary(v *Metric_Summary) {
// Called only when pool is enabled
v.Summary = nil
protoPoolMetric_Summary.Put(v)
}
func (m *Metric) GetSummary() *Summary {
if v, ok := m.GetData().(*Metric_Summary); ok {
return v.Summary
}
return nil
}
// Metric represents one metric as a collection of datapoints.
// See Metric definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto
type Metric struct {
Name string
Description string
Unit string
Data any
Metadata []KeyValue
}
var (
protoPoolMetric = sync.Pool{
New: func() any {
return &Metric{}
},
}
)
func NewMetric() *Metric {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Metric{}
}
return protoPoolMetric.Get().(*Metric)
}
func DeleteMetric(orig *Metric, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.deleteData()
for i := range orig.Metadata {
DeleteKeyValue(&orig.Metadata[i], false)
}
orig.Reset()
if nullable {
protoPoolMetric.Put(orig)
}
}
func CopyMetric(dest, src *Metric) *Metric {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewMetric()
}
dest.Name = src.Name
dest.Description = src.Description
dest.Unit = src.Unit
switch t := src.Data.(type) {
case *Metric_Gauge:
ov := NewMetric_Gauge()
ov.Gauge = NewGauge()
CopyGauge(ov.Gauge, t.Gauge)
dest.Data = ov
case *Metric_Sum:
ov := NewMetric_Sum()
ov.Sum = NewSum()
CopySum(ov.Sum, t.Sum)
dest.Data = ov
case *Metric_Histogram:
ov := NewMetric_Histogram()
ov.Histogram = NewHistogram()
CopyHistogram(ov.Histogram, t.Histogram)
dest.Data = ov
case *Metric_ExponentialHistogram:
ov := NewMetric_ExponentialHistogram()
ov.ExponentialHistogram = NewExponentialHistogram()
CopyExponentialHistogram(ov.ExponentialHistogram, t.ExponentialHistogram)
dest.Data = ov
case *Metric_Summary:
ov := NewMetric_Summary()
ov.Summary = NewSummary()
CopySummary(ov.Summary, t.Summary)
dest.Data = ov
default:
dest.Data = nil
}
dest.Metadata = CopyKeyValueSlice(dest.Metadata, src.Metadata)
return dest
}
func CopyMetricSlice(dest, src []Metric) []Metric {
var newDest []Metric
if cap(dest) < len(src) {
newDest = make([]Metric, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteMetric(&dest[i], false)
}
}
for i := range src {
CopyMetric(&newDest[i], &src[i])
}
return newDest
}
func CopyMetricPtrSlice(dest, src []*Metric) []*Metric {
var newDest []*Metric
if cap(dest) < len(src) {
newDest = make([]*Metric, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewMetric()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteMetric(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewMetric()
}
}
for i := range src {
CopyMetric(newDest[i], src[i])
}
return newDest
}
func (orig *Metric) Reset() {
*orig = Metric{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Metric) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.Name != "" {
dest.WriteObjectField("name")
dest.WriteString(orig.Name)
}
if orig.Description != "" {
dest.WriteObjectField("description")
dest.WriteString(orig.Description)
}
if orig.Unit != "" {
dest.WriteObjectField("unit")
dest.WriteString(orig.Unit)
}
switch orig := orig.Data.(type) {
case *Metric_Gauge:
if orig.Gauge != nil {
dest.WriteObjectField("gauge")
orig.Gauge.MarshalJSON(dest)
}
case *Metric_Sum:
if orig.Sum != nil {
dest.WriteObjectField("sum")
orig.Sum.MarshalJSON(dest)
}
case *Metric_Histogram:
if orig.Histogram != nil {
dest.WriteObjectField("histogram")
orig.Histogram.MarshalJSON(dest)
}
case *Metric_ExponentialHistogram:
if orig.ExponentialHistogram != nil {
dest.WriteObjectField("exponentialHistogram")
orig.ExponentialHistogram.MarshalJSON(dest)
}
case *Metric_Summary:
if orig.Summary != nil {
dest.WriteObjectField("summary")
orig.Summary.MarshalJSON(dest)
}
}
if len(orig.Metadata) > 0 {
dest.WriteObjectField("metadata")
dest.WriteArrayStart()
orig.Metadata[0].MarshalJSON(dest)
for i := 1; i < len(orig.Metadata); i++ {
dest.WriteMore()
orig.Metadata[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Metric) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "name":
orig.Name = iter.ReadString()
case "description":
orig.Description = iter.ReadString()
case "unit":
orig.Unit = iter.ReadString()
case "gauge":
{
ov := NewMetric_Gauge()
ov.Gauge = NewGauge()
ov.Gauge.UnmarshalJSON(iter)
orig.Data = ov
}
case "sum":
{
ov := NewMetric_Sum()
ov.Sum = NewSum()
ov.Sum.UnmarshalJSON(iter)
orig.Data = ov
}
case "histogram":
{
ov := NewMetric_Histogram()
ov.Histogram = NewHistogram()
ov.Histogram.UnmarshalJSON(iter)
orig.Data = ov
}
case "exponentialHistogram", "exponential_histogram":
{
ov := NewMetric_ExponentialHistogram()
ov.ExponentialHistogram = NewExponentialHistogram()
ov.ExponentialHistogram.UnmarshalJSON(iter)
orig.Data = ov
}
case "summary":
{
ov := NewMetric_Summary()
ov.Summary = NewSummary()
ov.Summary.UnmarshalJSON(iter)
orig.Data = ov
}
case "metadata":
for iter.ReadArray() {
orig.Metadata = append(orig.Metadata, KeyValue{})
orig.Metadata[len(orig.Metadata)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Metric) SizeProto() int {
var n int
var l int
_ = l
l = len(orig.Name)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.Description)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.Unit)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
switch orig := orig.Data.(type) {
case nil:
_ = orig
break
case *Metric_Gauge:
if orig.Gauge != nil {
l = orig.Gauge.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
case *Metric_Sum:
if orig.Sum != nil {
l = orig.Sum.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
case *Metric_Histogram:
if orig.Histogram != nil {
l = orig.Histogram.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
case *Metric_ExponentialHistogram:
if orig.ExponentialHistogram != nil {
l = orig.ExponentialHistogram.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
case *Metric_Summary:
if orig.Summary != nil {
l = orig.Summary.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
}
for i := range orig.Metadata {
l = orig.Metadata[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *Metric) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = len(orig.Name)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Name)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
l = len(orig.Description)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Description)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = len(orig.Unit)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Unit)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
switch orig := orig.Data.(type) {
case *Metric_Gauge:
if orig.Gauge != nil {
l = orig.Gauge.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x2a
}
case *Metric_Sum:
if orig.Sum != nil {
l = orig.Sum.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x3a
}
case *Metric_Histogram:
if orig.Histogram != nil {
l = orig.Histogram.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x4a
}
case *Metric_ExponentialHistogram:
if orig.ExponentialHistogram != nil {
l = orig.ExponentialHistogram.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x52
}
case *Metric_Summary:
if orig.Summary != nil {
l = orig.Summary.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x5a
}
}
for i := len(orig.Metadata) - 1; i >= 0; i-- {
l = orig.Metadata[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x62
}
return len(buf) - pos
}
func (orig *Metric) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Name = string(buf[startPos:pos])
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Description = string(buf[startPos:pos])
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Unit", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Unit = string(buf[startPos:pos])
case 5:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Gauge", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewMetric_Gauge()
ov.Gauge = NewGauge()
err = ov.Gauge.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
orig.Data = ov
case 7:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Sum", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewMetric_Sum()
ov.Sum = NewSum()
err = ov.Sum.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
orig.Data = ov
case 9:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Histogram", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewMetric_Histogram()
ov.Histogram = NewHistogram()
err = ov.Histogram.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
orig.Data = ov
case 10:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ExponentialHistogram", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewMetric_ExponentialHistogram()
ov.ExponentialHistogram = NewExponentialHistogram()
err = ov.ExponentialHistogram.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
orig.Data = ov
case 11:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Summary", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewMetric_Summary()
ov.Summary = NewSummary()
err = ov.Summary.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
orig.Data = ov
case 12:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Metadata = append(orig.Metadata, KeyValue{})
err = orig.Metadata[len(orig.Metadata)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestMetric() *Metric {
orig := NewMetric()
orig.Name = "test_name"
orig.Description = "test_description"
orig.Unit = "test_unit"
orig.Data = &Metric_Gauge{Gauge: GenTestGauge()}
orig.Metadata = []KeyValue{{}, *GenTestKeyValue()}
return orig
}
func GenTestMetricPtrSlice() []*Metric {
orig := make([]*Metric, 5)
orig[0] = NewMetric()
orig[1] = GenTestMetric()
orig[2] = NewMetric()
orig[3] = GenTestMetric()
orig[4] = NewMetric()
return orig
}
func GenTestMetricSlice() []Metric {
orig := make([]Metric, 5)
orig[1] = *GenTestMetric()
orig[3] = *GenTestMetric()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// MetricsData represents the metrics data that can be stored in a persistent storage,
// OR can be embedded by other protocols that transfer OTLP metrics data but do not
// implement the OTLP protocol..
type MetricsData struct {
ResourceMetrics []*ResourceMetrics
}
var (
protoPoolMetricsData = sync.Pool{
New: func() any {
return &MetricsData{}
},
}
)
func NewMetricsData() *MetricsData {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &MetricsData{}
}
return protoPoolMetricsData.Get().(*MetricsData)
}
func DeleteMetricsData(orig *MetricsData, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.ResourceMetrics {
DeleteResourceMetrics(orig.ResourceMetrics[i], true)
}
orig.Reset()
if nullable {
protoPoolMetricsData.Put(orig)
}
}
func CopyMetricsData(dest, src *MetricsData) *MetricsData {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewMetricsData()
}
dest.ResourceMetrics = CopyResourceMetricsPtrSlice(dest.ResourceMetrics, src.ResourceMetrics)
return dest
}
func CopyMetricsDataSlice(dest, src []MetricsData) []MetricsData {
var newDest []MetricsData
if cap(dest) < len(src) {
newDest = make([]MetricsData, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteMetricsData(&dest[i], false)
}
}
for i := range src {
CopyMetricsData(&newDest[i], &src[i])
}
return newDest
}
func CopyMetricsDataPtrSlice(dest, src []*MetricsData) []*MetricsData {
var newDest []*MetricsData
if cap(dest) < len(src) {
newDest = make([]*MetricsData, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewMetricsData()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteMetricsData(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewMetricsData()
}
}
for i := range src {
CopyMetricsData(newDest[i], src[i])
}
return newDest
}
func (orig *MetricsData) Reset() {
*orig = MetricsData{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *MetricsData) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.ResourceMetrics) > 0 {
dest.WriteObjectField("resourceMetrics")
dest.WriteArrayStart()
orig.ResourceMetrics[0].MarshalJSON(dest)
for i := 1; i < len(orig.ResourceMetrics); i++ {
dest.WriteMore()
orig.ResourceMetrics[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *MetricsData) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resourceMetrics", "resource_metrics":
for iter.ReadArray() {
orig.ResourceMetrics = append(orig.ResourceMetrics, NewResourceMetrics())
orig.ResourceMetrics[len(orig.ResourceMetrics)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *MetricsData) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.ResourceMetrics {
l = orig.ResourceMetrics[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *MetricsData) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.ResourceMetrics) - 1; i >= 0; i-- {
l = orig.ResourceMetrics[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *MetricsData) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ResourceMetrics", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ResourceMetrics = append(orig.ResourceMetrics, NewResourceMetrics())
err = orig.ResourceMetrics[len(orig.ResourceMetrics)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestMetricsData() *MetricsData {
orig := NewMetricsData()
orig.ResourceMetrics = []*ResourceMetrics{{}, GenTestResourceMetrics()}
return orig
}
func GenTestMetricsDataPtrSlice() []*MetricsData {
orig := make([]*MetricsData, 5)
orig[0] = NewMetricsData()
orig[1] = GenTestMetricsData()
orig[2] = NewMetricsData()
orig[3] = GenTestMetricsData()
orig[4] = NewMetricsData()
return orig
}
func GenTestMetricsDataSlice() []MetricsData {
orig := make([]MetricsData, 5)
orig[1] = *GenTestMetricsData()
orig[3] = *GenTestMetricsData()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type MetricsRequest struct {
RequestContext *RequestContext
MetricsData MetricsData
FormatVersion uint32
}
var (
protoPoolMetricsRequest = sync.Pool{
New: func() any {
return &MetricsRequest{}
},
}
)
func NewMetricsRequest() *MetricsRequest {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &MetricsRequest{}
}
return protoPoolMetricsRequest.Get().(*MetricsRequest)
}
func DeleteMetricsRequest(orig *MetricsRequest, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteRequestContext(orig.RequestContext, true)
DeleteMetricsData(&orig.MetricsData, false)
orig.Reset()
if nullable {
protoPoolMetricsRequest.Put(orig)
}
}
func CopyMetricsRequest(dest, src *MetricsRequest) *MetricsRequest {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewMetricsRequest()
}
dest.RequestContext = CopyRequestContext(dest.RequestContext, src.RequestContext)
CopyMetricsData(&dest.MetricsData, &src.MetricsData)
dest.FormatVersion = src.FormatVersion
return dest
}
func CopyMetricsRequestSlice(dest, src []MetricsRequest) []MetricsRequest {
var newDest []MetricsRequest
if cap(dest) < len(src) {
newDest = make([]MetricsRequest, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteMetricsRequest(&dest[i], false)
}
}
for i := range src {
CopyMetricsRequest(&newDest[i], &src[i])
}
return newDest
}
func CopyMetricsRequestPtrSlice(dest, src []*MetricsRequest) []*MetricsRequest {
var newDest []*MetricsRequest
if cap(dest) < len(src) {
newDest = make([]*MetricsRequest, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewMetricsRequest()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteMetricsRequest(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewMetricsRequest()
}
}
for i := range src {
CopyMetricsRequest(newDest[i], src[i])
}
return newDest
}
func (orig *MetricsRequest) Reset() {
*orig = MetricsRequest{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *MetricsRequest) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.RequestContext != nil {
dest.WriteObjectField("requestContext")
orig.RequestContext.MarshalJSON(dest)
}
dest.WriteObjectField("metricsData")
orig.MetricsData.MarshalJSON(dest)
if orig.FormatVersion != uint32(0) {
dest.WriteObjectField("formatVersion")
dest.WriteUint32(orig.FormatVersion)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *MetricsRequest) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "requestContext", "request_context":
orig.RequestContext = NewRequestContext()
orig.RequestContext.UnmarshalJSON(iter)
case "metricsData", "metrics_data":
orig.MetricsData.UnmarshalJSON(iter)
case "formatVersion", "format_version":
orig.FormatVersion = iter.ReadUint32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *MetricsRequest) SizeProto() int {
var n int
var l int
_ = l
if orig.RequestContext != nil {
l = orig.RequestContext.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = orig.MetricsData.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.FormatVersion != uint32(0) {
n += 5
}
return n
}
func (orig *MetricsRequest) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.RequestContext != nil {
l = orig.RequestContext.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = orig.MetricsData.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
if orig.FormatVersion != uint32(0) {
pos -= 4
binary.LittleEndian.PutUint32(buf[pos:], uint32(orig.FormatVersion))
pos--
buf[pos] = 0xd
}
return len(buf) - pos
}
func (orig *MetricsRequest) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field RequestContext", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.RequestContext = NewRequestContext()
err = orig.RequestContext.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field MetricsData", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.MetricsData.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 1:
if wireType != proto.WireTypeI32 {
return fmt.Errorf("proto: wrong wireType = %d for field FormatVersion", wireType)
}
var num uint32
num, pos, err = proto.ConsumeI32(buf, pos)
if err != nil {
return err
}
orig.FormatVersion = uint32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestMetricsRequest() *MetricsRequest {
orig := NewMetricsRequest()
orig.RequestContext = GenTestRequestContext()
orig.MetricsData = *GenTestMetricsData()
orig.FormatVersion = uint32(13)
return orig
}
func GenTestMetricsRequestPtrSlice() []*MetricsRequest {
orig := make([]*MetricsRequest, 5)
orig[0] = NewMetricsRequest()
orig[1] = GenTestMetricsRequest()
orig[2] = NewMetricsRequest()
orig[3] = GenTestMetricsRequest()
orig[4] = NewMetricsRequest()
return orig
}
func GenTestMetricsRequestSlice() []MetricsRequest {
orig := make([]MetricsRequest, 5)
orig[1] = *GenTestMetricsRequest()
orig[3] = *GenTestMetricsRequest()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"math"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
func (m *NumberDataPoint) GetValue() any {
if m != nil {
return m.Value
}
return nil
}
func (m *NumberDataPoint) deleteValue() {
if m == nil {
return
}
switch ov := m.Value.(type) {
case *NumberDataPoint_AsDouble:
deleteNumberDataPoint_AsDouble(ov)
case *NumberDataPoint_AsInt:
deleteNumberDataPoint_AsInt(ov)
}
m.Value = nil
}
var (
protoPoolNumberDataPoint_AsDouble = sync.Pool{
New: func() any {
return &NumberDataPoint_AsDouble{}
},
}
)
type NumberDataPoint_AsDouble struct {
AsDouble float64
}
func NewNumberDataPoint_AsDouble() *NumberDataPoint_AsDouble {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &NumberDataPoint_AsDouble{}
}
return protoPoolNumberDataPoint_AsDouble.Get().(*NumberDataPoint_AsDouble)
}
func deleteNumberDataPoint_AsDouble(v *NumberDataPoint_AsDouble) {
// Called only when pool is enabled
v.AsDouble = float64(0)
protoPoolNumberDataPoint_AsDouble.Put(v)
}
func (m *NumberDataPoint) GetAsDouble() float64 {
if v, ok := m.GetValue().(*NumberDataPoint_AsDouble); ok {
return v.AsDouble
}
return float64(0)
}
func (m *NumberDataPoint) SetAsDouble(val float64) {
if m.Value != nil {
// Reuse message if possible, otherwise delete and create a new one.
if v, ok := m.GetValue().(*NumberDataPoint_AsDouble); ok {
v.AsDouble = val
return
}
m.deleteValue()
}
v := NewNumberDataPoint_AsDouble()
v.AsDouble = val
m.Value = v
}
var (
protoPoolNumberDataPoint_AsInt = sync.Pool{
New: func() any {
return &NumberDataPoint_AsInt{}
},
}
)
type NumberDataPoint_AsInt struct {
AsInt int64
}
func NewNumberDataPoint_AsInt() *NumberDataPoint_AsInt {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &NumberDataPoint_AsInt{}
}
return protoPoolNumberDataPoint_AsInt.Get().(*NumberDataPoint_AsInt)
}
func deleteNumberDataPoint_AsInt(v *NumberDataPoint_AsInt) {
// Called only when pool is enabled
v.AsInt = int64(0)
protoPoolNumberDataPoint_AsInt.Put(v)
}
func (m *NumberDataPoint) GetAsInt() int64 {
if v, ok := m.GetValue().(*NumberDataPoint_AsInt); ok {
return v.AsInt
}
return int64(0)
}
func (m *NumberDataPoint) SetAsInt(val int64) {
if m.Value != nil {
// Reuse message if possible, otherwise delete and create a new one.
if v, ok := m.GetValue().(*NumberDataPoint_AsInt); ok {
v.AsInt = val
return
}
m.deleteValue()
}
v := NewNumberDataPoint_AsInt()
v.AsInt = val
m.Value = v
}
// NumberDataPoint is a single data point in a timeseries that describes the time-varying value of a number metric.
type NumberDataPoint struct {
Value any
Attributes []KeyValue
Exemplars []Exemplar
StartTimeUnixNano uint64
TimeUnixNano uint64
Flags uint32
}
var (
protoPoolNumberDataPoint = sync.Pool{
New: func() any {
return &NumberDataPoint{}
},
}
)
func NewNumberDataPoint() *NumberDataPoint {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &NumberDataPoint{}
}
return protoPoolNumberDataPoint.Get().(*NumberDataPoint)
}
func DeleteNumberDataPoint(orig *NumberDataPoint, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.Attributes {
DeleteKeyValue(&orig.Attributes[i], false)
}
orig.deleteValue()
for i := range orig.Exemplars {
DeleteExemplar(&orig.Exemplars[i], false)
}
orig.Reset()
if nullable {
protoPoolNumberDataPoint.Put(orig)
}
}
func CopyNumberDataPoint(dest, src *NumberDataPoint) *NumberDataPoint {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewNumberDataPoint()
}
dest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)
dest.StartTimeUnixNano = src.StartTimeUnixNano
dest.TimeUnixNano = src.TimeUnixNano
switch t := src.Value.(type) {
case *NumberDataPoint_AsDouble:
ov := NewNumberDataPoint_AsDouble()
ov.AsDouble = t.AsDouble
dest.Value = ov
case *NumberDataPoint_AsInt:
ov := NewNumberDataPoint_AsInt()
ov.AsInt = t.AsInt
dest.Value = ov
default:
dest.Value = nil
}
dest.Exemplars = CopyExemplarSlice(dest.Exemplars, src.Exemplars)
dest.Flags = src.Flags
return dest
}
func CopyNumberDataPointSlice(dest, src []NumberDataPoint) []NumberDataPoint {
var newDest []NumberDataPoint
if cap(dest) < len(src) {
newDest = make([]NumberDataPoint, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteNumberDataPoint(&dest[i], false)
}
}
for i := range src {
CopyNumberDataPoint(&newDest[i], &src[i])
}
return newDest
}
func CopyNumberDataPointPtrSlice(dest, src []*NumberDataPoint) []*NumberDataPoint {
var newDest []*NumberDataPoint
if cap(dest) < len(src) {
newDest = make([]*NumberDataPoint, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewNumberDataPoint()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteNumberDataPoint(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewNumberDataPoint()
}
}
for i := range src {
CopyNumberDataPoint(newDest[i], src[i])
}
return newDest
}
func (orig *NumberDataPoint) Reset() {
*orig = NumberDataPoint{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *NumberDataPoint) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.Attributes) > 0 {
dest.WriteObjectField("attributes")
dest.WriteArrayStart()
orig.Attributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.Attributes); i++ {
dest.WriteMore()
orig.Attributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.StartTimeUnixNano != uint64(0) {
dest.WriteObjectField("startTimeUnixNano")
dest.WriteUint64(orig.StartTimeUnixNano)
}
if orig.TimeUnixNano != uint64(0) {
dest.WriteObjectField("timeUnixNano")
dest.WriteUint64(orig.TimeUnixNano)
}
switch orig := orig.Value.(type) {
case *NumberDataPoint_AsDouble:
dest.WriteObjectField("asDouble")
dest.WriteFloat64(orig.AsDouble)
case *NumberDataPoint_AsInt:
dest.WriteObjectField("asInt")
dest.WriteInt64(orig.AsInt)
}
if len(orig.Exemplars) > 0 {
dest.WriteObjectField("exemplars")
dest.WriteArrayStart()
orig.Exemplars[0].MarshalJSON(dest)
for i := 1; i < len(orig.Exemplars); i++ {
dest.WriteMore()
orig.Exemplars[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.Flags != uint32(0) {
dest.WriteObjectField("flags")
dest.WriteUint32(orig.Flags)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *NumberDataPoint) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "attributes":
for iter.ReadArray() {
orig.Attributes = append(orig.Attributes, KeyValue{})
orig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)
}
case "startTimeUnixNano", "start_time_unix_nano":
orig.StartTimeUnixNano = iter.ReadUint64()
case "timeUnixNano", "time_unix_nano":
orig.TimeUnixNano = iter.ReadUint64()
case "asDouble", "as_double":
{
ov := NewNumberDataPoint_AsDouble()
ov.AsDouble = iter.ReadFloat64()
orig.Value = ov
}
case "asInt", "as_int":
{
ov := NewNumberDataPoint_AsInt()
ov.AsInt = iter.ReadInt64()
orig.Value = ov
}
case "exemplars":
for iter.ReadArray() {
orig.Exemplars = append(orig.Exemplars, Exemplar{})
orig.Exemplars[len(orig.Exemplars)-1].UnmarshalJSON(iter)
}
case "flags":
orig.Flags = iter.ReadUint32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *NumberDataPoint) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.Attributes {
l = orig.Attributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.StartTimeUnixNano != uint64(0) {
n += 9
}
if orig.TimeUnixNano != uint64(0) {
n += 9
}
switch orig := orig.Value.(type) {
case nil:
_ = orig
break
case *NumberDataPoint_AsDouble:
n += 9
case *NumberDataPoint_AsInt:
n += 9
}
for i := range orig.Exemplars {
l = orig.Exemplars[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.Flags != uint32(0) {
n += 1 + proto.Sov(uint64(orig.Flags))
}
return n
}
func (orig *NumberDataPoint) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.Attributes) - 1; i >= 0; i-- {
l = orig.Attributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x3a
}
if orig.StartTimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.StartTimeUnixNano))
pos--
buf[pos] = 0x11
}
if orig.TimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))
pos--
buf[pos] = 0x19
}
switch orig := orig.Value.(type) {
case *NumberDataPoint_AsDouble:
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.AsDouble))
pos--
buf[pos] = 0x21
case *NumberDataPoint_AsInt:
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.AsInt))
pos--
buf[pos] = 0x31
}
for i := len(orig.Exemplars) - 1; i >= 0; i-- {
l = orig.Exemplars[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x2a
}
if orig.Flags != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Flags))
pos--
buf[pos] = 0x40
}
return len(buf) - pos
}
func (orig *NumberDataPoint) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 7:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Attributes = append(orig.Attributes, KeyValue{})
err = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field StartTimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.StartTimeUnixNano = uint64(num)
case 3:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field TimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.TimeUnixNano = uint64(num)
case 4:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field AsDouble", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
ov := NewNumberDataPoint_AsDouble()
ov.AsDouble = math.Float64frombits(num)
orig.Value = ov
case 6:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field AsInt", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
ov := NewNumberDataPoint_AsInt()
ov.AsInt = int64(num)
orig.Value = ov
case 5:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Exemplars", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Exemplars = append(orig.Exemplars, Exemplar{})
err = orig.Exemplars[len(orig.Exemplars)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 8:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Flags", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Flags = uint32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestNumberDataPoint() *NumberDataPoint {
orig := NewNumberDataPoint()
orig.Attributes = []KeyValue{{}, *GenTestKeyValue()}
orig.StartTimeUnixNano = uint64(13)
orig.TimeUnixNano = uint64(13)
orig.Value = &NumberDataPoint_AsDouble{AsDouble: float64(3.1415926)}
orig.Exemplars = []Exemplar{{}, *GenTestExemplar()}
orig.Flags = uint32(13)
return orig
}
func GenTestNumberDataPointPtrSlice() []*NumberDataPoint {
orig := make([]*NumberDataPoint, 5)
orig[0] = NewNumberDataPoint()
orig[1] = GenTestNumberDataPoint()
orig[2] = NewNumberDataPoint()
orig[3] = GenTestNumberDataPoint()
orig[4] = NewNumberDataPoint()
return orig
}
func GenTestNumberDataPointSlice() []NumberDataPoint {
orig := make([]NumberDataPoint, 5)
orig[1] = *GenTestNumberDataPoint()
orig[3] = *GenTestNumberDataPoint()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Profile are an implementation of the pprofextended data model.
type Profile struct {
OriginalPayloadFormat string
Samples []*Sample
OriginalPayload []byte
AttributeIndices []int32
TimeUnixNano uint64
DurationNano uint64
Period int64
SampleType ValueType
PeriodType ValueType
DroppedAttributesCount uint32
ProfileId ProfileID
}
var (
protoPoolProfile = sync.Pool{
New: func() any {
return &Profile{}
},
}
)
func NewProfile() *Profile {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Profile{}
}
return protoPoolProfile.Get().(*Profile)
}
func DeleteProfile(orig *Profile, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteValueType(&orig.SampleType, false)
for i := range orig.Samples {
DeleteSample(orig.Samples[i], true)
}
DeleteValueType(&orig.PeriodType, false)
DeleteProfileID(&orig.ProfileId, false)
orig.Reset()
if nullable {
protoPoolProfile.Put(orig)
}
}
func CopyProfile(dest, src *Profile) *Profile {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewProfile()
}
CopyValueType(&dest.SampleType, &src.SampleType)
dest.Samples = CopySamplePtrSlice(dest.Samples, src.Samples)
dest.TimeUnixNano = src.TimeUnixNano
dest.DurationNano = src.DurationNano
CopyValueType(&dest.PeriodType, &src.PeriodType)
dest.Period = src.Period
CopyProfileID(&dest.ProfileId, &src.ProfileId)
dest.DroppedAttributesCount = src.DroppedAttributesCount
dest.OriginalPayloadFormat = src.OriginalPayloadFormat
dest.OriginalPayload = src.OriginalPayload
dest.AttributeIndices = append(dest.AttributeIndices[:0], src.AttributeIndices...)
return dest
}
func CopyProfileSlice(dest, src []Profile) []Profile {
var newDest []Profile
if cap(dest) < len(src) {
newDest = make([]Profile, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteProfile(&dest[i], false)
}
}
for i := range src {
CopyProfile(&newDest[i], &src[i])
}
return newDest
}
func CopyProfilePtrSlice(dest, src []*Profile) []*Profile {
var newDest []*Profile
if cap(dest) < len(src) {
newDest = make([]*Profile, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewProfile()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteProfile(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewProfile()
}
}
for i := range src {
CopyProfile(newDest[i], src[i])
}
return newDest
}
func (orig *Profile) Reset() {
*orig = Profile{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Profile) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("sampleType")
orig.SampleType.MarshalJSON(dest)
if len(orig.Samples) > 0 {
dest.WriteObjectField("samples")
dest.WriteArrayStart()
orig.Samples[0].MarshalJSON(dest)
for i := 1; i < len(orig.Samples); i++ {
dest.WriteMore()
orig.Samples[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.TimeUnixNano != uint64(0) {
dest.WriteObjectField("timeUnixNano")
dest.WriteUint64(orig.TimeUnixNano)
}
if orig.DurationNano != uint64(0) {
dest.WriteObjectField("durationNano")
dest.WriteUint64(orig.DurationNano)
}
dest.WriteObjectField("periodType")
orig.PeriodType.MarshalJSON(dest)
if orig.Period != int64(0) {
dest.WriteObjectField("period")
dest.WriteInt64(orig.Period)
}
if !orig.ProfileId.IsEmpty() {
dest.WriteObjectField("profileId")
orig.ProfileId.MarshalJSON(dest)
}
if orig.DroppedAttributesCount != uint32(0) {
dest.WriteObjectField("droppedAttributesCount")
dest.WriteUint32(orig.DroppedAttributesCount)
}
if orig.OriginalPayloadFormat != "" {
dest.WriteObjectField("originalPayloadFormat")
dest.WriteString(orig.OriginalPayloadFormat)
}
if len(orig.OriginalPayload) > 0 {
dest.WriteObjectField("originalPayload")
dest.WriteBytes(orig.OriginalPayload)
}
if len(orig.AttributeIndices) > 0 {
dest.WriteObjectField("attributeIndices")
dest.WriteArrayStart()
dest.WriteInt32(orig.AttributeIndices[0])
for i := 1; i < len(orig.AttributeIndices); i++ {
dest.WriteMore()
dest.WriteInt32(orig.AttributeIndices[i])
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Profile) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "sampleType", "sample_type":
orig.SampleType.UnmarshalJSON(iter)
case "samples":
for iter.ReadArray() {
orig.Samples = append(orig.Samples, NewSample())
orig.Samples[len(orig.Samples)-1].UnmarshalJSON(iter)
}
case "timeUnixNano", "time_unix_nano":
orig.TimeUnixNano = iter.ReadUint64()
case "durationNano", "duration_nano":
orig.DurationNano = iter.ReadUint64()
case "periodType", "period_type":
orig.PeriodType.UnmarshalJSON(iter)
case "period":
orig.Period = iter.ReadInt64()
case "profileId", "profile_id":
orig.ProfileId.UnmarshalJSON(iter)
case "droppedAttributesCount", "dropped_attributes_count":
orig.DroppedAttributesCount = iter.ReadUint32()
case "originalPayloadFormat", "original_payload_format":
orig.OriginalPayloadFormat = iter.ReadString()
case "originalPayload", "original_payload":
orig.OriginalPayload = iter.ReadBytes()
case "attributeIndices", "attribute_indices":
for iter.ReadArray() {
orig.AttributeIndices = append(orig.AttributeIndices, iter.ReadInt32())
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Profile) SizeProto() int {
var n int
var l int
_ = l
l = orig.SampleType.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
for i := range orig.Samples {
l = orig.Samples[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.TimeUnixNano != uint64(0) {
n += 9
}
if orig.DurationNano != uint64(0) {
n += 1 + proto.Sov(uint64(orig.DurationNano))
}
l = orig.PeriodType.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.Period != int64(0) {
n += 1 + proto.Sov(uint64(orig.Period))
}
l = orig.ProfileId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.DroppedAttributesCount != uint32(0) {
n += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))
}
l = len(orig.OriginalPayloadFormat)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.OriginalPayload)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
if len(orig.AttributeIndices) > 0 {
l = 0
for _, e := range orig.AttributeIndices {
l += proto.Sov(uint64(e))
}
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *Profile) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.SampleType.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
for i := len(orig.Samples) - 1; i >= 0; i-- {
l = orig.Samples[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
if orig.TimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))
pos--
buf[pos] = 0x19
}
if orig.DurationNano != uint64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.DurationNano))
pos--
buf[pos] = 0x20
}
l = orig.PeriodType.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x2a
if orig.Period != int64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Period))
pos--
buf[pos] = 0x30
}
l = orig.ProfileId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x3a
if orig.DroppedAttributesCount != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))
pos--
buf[pos] = 0x40
}
l = len(orig.OriginalPayloadFormat)
if l > 0 {
pos -= l
copy(buf[pos:], orig.OriginalPayloadFormat)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x4a
}
l = len(orig.OriginalPayload)
if l > 0 {
pos -= l
copy(buf[pos:], orig.OriginalPayload)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x52
}
l = len(orig.AttributeIndices)
if l > 0 {
endPos := pos
for i := l - 1; i >= 0; i-- {
pos = proto.EncodeVarint(buf, pos, uint64(orig.AttributeIndices[i]))
}
pos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))
pos--
buf[pos] = 0x5a
}
return len(buf) - pos
}
func (orig *Profile) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SampleType", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.SampleType.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Samples", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Samples = append(orig.Samples, NewSample())
err = orig.Samples[len(orig.Samples)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field TimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.TimeUnixNano = uint64(num)
case 4:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field DurationNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.DurationNano = uint64(num)
case 5:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field PeriodType", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.PeriodType.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 6:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Period", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Period = int64(num)
case 7:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ProfileId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.ProfileId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 8:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field DroppedAttributesCount", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.DroppedAttributesCount = uint32(num)
case 9:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field OriginalPayloadFormat", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.OriginalPayloadFormat = string(buf[startPos:pos])
case 10:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field OriginalPayload", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
if length != 0 {
orig.OriginalPayload = make([]byte, length)
copy(orig.OriginalPayload, buf[startPos:pos])
}
case 11:
switch wireType {
case proto.WireTypeLen:
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
var num uint64
for startPos < pos {
num, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)
if err != nil {
return err
}
orig.AttributeIndices = append(orig.AttributeIndices, int32(num))
}
if startPos != pos {
return fmt.Errorf("proto: invalid field len = %d for field AttributeIndices", pos-startPos)
}
case proto.WireTypeVarint:
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.AttributeIndices = append(orig.AttributeIndices, int32(num))
default:
return fmt.Errorf("proto: wrong wireType = %d for field AttributeIndices", wireType)
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestProfile() *Profile {
orig := NewProfile()
orig.SampleType = *GenTestValueType()
orig.Samples = []*Sample{{}, GenTestSample()}
orig.TimeUnixNano = uint64(13)
orig.DurationNano = uint64(13)
orig.PeriodType = *GenTestValueType()
orig.Period = int64(13)
orig.ProfileId = *GenTestProfileID()
orig.DroppedAttributesCount = uint32(13)
orig.OriginalPayloadFormat = "test_originalpayloadformat"
orig.OriginalPayload = []byte{1, 2, 3}
orig.AttributeIndices = []int32{int32(0), int32(13)}
return orig
}
func GenTestProfilePtrSlice() []*Profile {
orig := make([]*Profile, 5)
orig[0] = NewProfile()
orig[1] = GenTestProfile()
orig[2] = NewProfile()
orig[3] = GenTestProfile()
orig[4] = NewProfile()
return orig
}
func GenTestProfileSlice() []Profile {
orig := make([]Profile, 5)
orig[1] = *GenTestProfile()
orig[3] = *GenTestProfile()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ProfilesData represents the profiles data that can be stored in persistent storage,
// OR can be embedded by other protocols that transfer OTLP profiles data but do not
// implement the OTLP protocol.
type ProfilesData struct {
ResourceProfiles []*ResourceProfiles
Dictionary ProfilesDictionary
}
var (
protoPoolProfilesData = sync.Pool{
New: func() any {
return &ProfilesData{}
},
}
)
func NewProfilesData() *ProfilesData {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ProfilesData{}
}
return protoPoolProfilesData.Get().(*ProfilesData)
}
func DeleteProfilesData(orig *ProfilesData, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.ResourceProfiles {
DeleteResourceProfiles(orig.ResourceProfiles[i], true)
}
DeleteProfilesDictionary(&orig.Dictionary, false)
orig.Reset()
if nullable {
protoPoolProfilesData.Put(orig)
}
}
func CopyProfilesData(dest, src *ProfilesData) *ProfilesData {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewProfilesData()
}
dest.ResourceProfiles = CopyResourceProfilesPtrSlice(dest.ResourceProfiles, src.ResourceProfiles)
CopyProfilesDictionary(&dest.Dictionary, &src.Dictionary)
return dest
}
func CopyProfilesDataSlice(dest, src []ProfilesData) []ProfilesData {
var newDest []ProfilesData
if cap(dest) < len(src) {
newDest = make([]ProfilesData, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteProfilesData(&dest[i], false)
}
}
for i := range src {
CopyProfilesData(&newDest[i], &src[i])
}
return newDest
}
func CopyProfilesDataPtrSlice(dest, src []*ProfilesData) []*ProfilesData {
var newDest []*ProfilesData
if cap(dest) < len(src) {
newDest = make([]*ProfilesData, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewProfilesData()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteProfilesData(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewProfilesData()
}
}
for i := range src {
CopyProfilesData(newDest[i], src[i])
}
return newDest
}
func (orig *ProfilesData) Reset() {
*orig = ProfilesData{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ProfilesData) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.ResourceProfiles) > 0 {
dest.WriteObjectField("resourceProfiles")
dest.WriteArrayStart()
orig.ResourceProfiles[0].MarshalJSON(dest)
for i := 1; i < len(orig.ResourceProfiles); i++ {
dest.WriteMore()
orig.ResourceProfiles[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectField("dictionary")
orig.Dictionary.MarshalJSON(dest)
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ProfilesData) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resourceProfiles", "resource_profiles":
for iter.ReadArray() {
orig.ResourceProfiles = append(orig.ResourceProfiles, NewResourceProfiles())
orig.ResourceProfiles[len(orig.ResourceProfiles)-1].UnmarshalJSON(iter)
}
case "dictionary":
orig.Dictionary.UnmarshalJSON(iter)
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ProfilesData) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.ResourceProfiles {
l = orig.ResourceProfiles[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = orig.Dictionary.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
return n
}
func (orig *ProfilesData) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.ResourceProfiles) - 1; i >= 0; i-- {
l = orig.ResourceProfiles[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
l = orig.Dictionary.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
return len(buf) - pos
}
func (orig *ProfilesData) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ResourceProfiles", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ResourceProfiles = append(orig.ResourceProfiles, NewResourceProfiles())
err = orig.ResourceProfiles[len(orig.ResourceProfiles)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Dictionary", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Dictionary.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestProfilesData() *ProfilesData {
orig := NewProfilesData()
orig.ResourceProfiles = []*ResourceProfiles{{}, GenTestResourceProfiles()}
orig.Dictionary = *GenTestProfilesDictionary()
return orig
}
func GenTestProfilesDataPtrSlice() []*ProfilesData {
orig := make([]*ProfilesData, 5)
orig[0] = NewProfilesData()
orig[1] = GenTestProfilesData()
orig[2] = NewProfilesData()
orig[3] = GenTestProfilesData()
orig[4] = NewProfilesData()
return orig
}
func GenTestProfilesDataSlice() []ProfilesData {
orig := make([]ProfilesData, 5)
orig[1] = *GenTestProfilesData()
orig[3] = *GenTestProfilesData()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ProfilesDictionary is the reference table containing all data shared by profiles across the message being sent.
type ProfilesDictionary struct {
MappingTable []*Mapping
LocationTable []*Location
FunctionTable []*Function
LinkTable []*Link
StringTable []string
AttributeTable []*KeyValueAndUnit
StackTable []*Stack
}
var (
protoPoolProfilesDictionary = sync.Pool{
New: func() any {
return &ProfilesDictionary{}
},
}
)
func NewProfilesDictionary() *ProfilesDictionary {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ProfilesDictionary{}
}
return protoPoolProfilesDictionary.Get().(*ProfilesDictionary)
}
func DeleteProfilesDictionary(orig *ProfilesDictionary, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.MappingTable {
DeleteMapping(orig.MappingTable[i], true)
}
for i := range orig.LocationTable {
DeleteLocation(orig.LocationTable[i], true)
}
for i := range orig.FunctionTable {
DeleteFunction(orig.FunctionTable[i], true)
}
for i := range orig.LinkTable {
DeleteLink(orig.LinkTable[i], true)
}
for i := range orig.AttributeTable {
DeleteKeyValueAndUnit(orig.AttributeTable[i], true)
}
for i := range orig.StackTable {
DeleteStack(orig.StackTable[i], true)
}
orig.Reset()
if nullable {
protoPoolProfilesDictionary.Put(orig)
}
}
func CopyProfilesDictionary(dest, src *ProfilesDictionary) *ProfilesDictionary {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewProfilesDictionary()
}
dest.MappingTable = CopyMappingPtrSlice(dest.MappingTable, src.MappingTable)
dest.LocationTable = CopyLocationPtrSlice(dest.LocationTable, src.LocationTable)
dest.FunctionTable = CopyFunctionPtrSlice(dest.FunctionTable, src.FunctionTable)
dest.LinkTable = CopyLinkPtrSlice(dest.LinkTable, src.LinkTable)
dest.StringTable = append(dest.StringTable[:0], src.StringTable...)
dest.AttributeTable = CopyKeyValueAndUnitPtrSlice(dest.AttributeTable, src.AttributeTable)
dest.StackTable = CopyStackPtrSlice(dest.StackTable, src.StackTable)
return dest
}
func CopyProfilesDictionarySlice(dest, src []ProfilesDictionary) []ProfilesDictionary {
var newDest []ProfilesDictionary
if cap(dest) < len(src) {
newDest = make([]ProfilesDictionary, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteProfilesDictionary(&dest[i], false)
}
}
for i := range src {
CopyProfilesDictionary(&newDest[i], &src[i])
}
return newDest
}
func CopyProfilesDictionaryPtrSlice(dest, src []*ProfilesDictionary) []*ProfilesDictionary {
var newDest []*ProfilesDictionary
if cap(dest) < len(src) {
newDest = make([]*ProfilesDictionary, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewProfilesDictionary()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteProfilesDictionary(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewProfilesDictionary()
}
}
for i := range src {
CopyProfilesDictionary(newDest[i], src[i])
}
return newDest
}
func (orig *ProfilesDictionary) Reset() {
*orig = ProfilesDictionary{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ProfilesDictionary) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.MappingTable) > 0 {
dest.WriteObjectField("mappingTable")
dest.WriteArrayStart()
orig.MappingTable[0].MarshalJSON(dest)
for i := 1; i < len(orig.MappingTable); i++ {
dest.WriteMore()
orig.MappingTable[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if len(orig.LocationTable) > 0 {
dest.WriteObjectField("locationTable")
dest.WriteArrayStart()
orig.LocationTable[0].MarshalJSON(dest)
for i := 1; i < len(orig.LocationTable); i++ {
dest.WriteMore()
orig.LocationTable[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if len(orig.FunctionTable) > 0 {
dest.WriteObjectField("functionTable")
dest.WriteArrayStart()
orig.FunctionTable[0].MarshalJSON(dest)
for i := 1; i < len(orig.FunctionTable); i++ {
dest.WriteMore()
orig.FunctionTable[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if len(orig.LinkTable) > 0 {
dest.WriteObjectField("linkTable")
dest.WriteArrayStart()
orig.LinkTable[0].MarshalJSON(dest)
for i := 1; i < len(orig.LinkTable); i++ {
dest.WriteMore()
orig.LinkTable[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if len(orig.StringTable) > 0 {
dest.WriteObjectField("stringTable")
dest.WriteArrayStart()
dest.WriteString(orig.StringTable[0])
for i := 1; i < len(orig.StringTable); i++ {
dest.WriteMore()
dest.WriteString(orig.StringTable[i])
}
dest.WriteArrayEnd()
}
if len(orig.AttributeTable) > 0 {
dest.WriteObjectField("attributeTable")
dest.WriteArrayStart()
orig.AttributeTable[0].MarshalJSON(dest)
for i := 1; i < len(orig.AttributeTable); i++ {
dest.WriteMore()
orig.AttributeTable[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if len(orig.StackTable) > 0 {
dest.WriteObjectField("stackTable")
dest.WriteArrayStart()
orig.StackTable[0].MarshalJSON(dest)
for i := 1; i < len(orig.StackTable); i++ {
dest.WriteMore()
orig.StackTable[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ProfilesDictionary) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "mappingTable", "mapping_table":
for iter.ReadArray() {
orig.MappingTable = append(orig.MappingTable, NewMapping())
orig.MappingTable[len(orig.MappingTable)-1].UnmarshalJSON(iter)
}
case "locationTable", "location_table":
for iter.ReadArray() {
orig.LocationTable = append(orig.LocationTable, NewLocation())
orig.LocationTable[len(orig.LocationTable)-1].UnmarshalJSON(iter)
}
case "functionTable", "function_table":
for iter.ReadArray() {
orig.FunctionTable = append(orig.FunctionTable, NewFunction())
orig.FunctionTable[len(orig.FunctionTable)-1].UnmarshalJSON(iter)
}
case "linkTable", "link_table":
for iter.ReadArray() {
orig.LinkTable = append(orig.LinkTable, NewLink())
orig.LinkTable[len(orig.LinkTable)-1].UnmarshalJSON(iter)
}
case "stringTable", "string_table":
for iter.ReadArray() {
orig.StringTable = append(orig.StringTable, iter.ReadString())
}
case "attributeTable", "attribute_table":
for iter.ReadArray() {
orig.AttributeTable = append(orig.AttributeTable, NewKeyValueAndUnit())
orig.AttributeTable[len(orig.AttributeTable)-1].UnmarshalJSON(iter)
}
case "stackTable", "stack_table":
for iter.ReadArray() {
orig.StackTable = append(orig.StackTable, NewStack())
orig.StackTable[len(orig.StackTable)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ProfilesDictionary) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.MappingTable {
l = orig.MappingTable[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.LocationTable {
l = orig.LocationTable[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.FunctionTable {
l = orig.FunctionTable[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.LinkTable {
l = orig.LinkTable[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
for _, s := range orig.StringTable {
l = len(s)
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.AttributeTable {
l = orig.AttributeTable[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.StackTable {
l = orig.StackTable[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ProfilesDictionary) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.MappingTable) - 1; i >= 0; i-- {
l = orig.MappingTable[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
for i := len(orig.LocationTable) - 1; i >= 0; i-- {
l = orig.LocationTable[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
for i := len(orig.FunctionTable) - 1; i >= 0; i-- {
l = orig.FunctionTable[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
for i := len(orig.LinkTable) - 1; i >= 0; i-- {
l = orig.LinkTable[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x22
}
for i := len(orig.StringTable) - 1; i >= 0; i-- {
l = len(orig.StringTable[i])
pos -= l
copy(buf[pos:], orig.StringTable[i])
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x2a
}
for i := len(orig.AttributeTable) - 1; i >= 0; i-- {
l = orig.AttributeTable[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x32
}
for i := len(orig.StackTable) - 1; i >= 0; i-- {
l = orig.StackTable[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x3a
}
return len(buf) - pos
}
func (orig *ProfilesDictionary) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field MappingTable", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.MappingTable = append(orig.MappingTable, NewMapping())
err = orig.MappingTable[len(orig.MappingTable)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field LocationTable", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.LocationTable = append(orig.LocationTable, NewLocation())
err = orig.LocationTable[len(orig.LocationTable)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field FunctionTable", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.FunctionTable = append(orig.FunctionTable, NewFunction())
err = orig.FunctionTable[len(orig.FunctionTable)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 4:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field LinkTable", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.LinkTable = append(orig.LinkTable, NewLink())
err = orig.LinkTable[len(orig.LinkTable)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 5:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field StringTable", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.StringTable = append(orig.StringTable, string(buf[startPos:pos]))
case 6:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field AttributeTable", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.AttributeTable = append(orig.AttributeTable, NewKeyValueAndUnit())
err = orig.AttributeTable[len(orig.AttributeTable)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 7:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field StackTable", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.StackTable = append(orig.StackTable, NewStack())
err = orig.StackTable[len(orig.StackTable)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestProfilesDictionary() *ProfilesDictionary {
orig := NewProfilesDictionary()
orig.MappingTable = []*Mapping{{}, GenTestMapping()}
orig.LocationTable = []*Location{{}, GenTestLocation()}
orig.FunctionTable = []*Function{{}, GenTestFunction()}
orig.LinkTable = []*Link{{}, GenTestLink()}
orig.StringTable = []string{"", "test_stringtable"}
orig.AttributeTable = []*KeyValueAndUnit{{}, GenTestKeyValueAndUnit()}
orig.StackTable = []*Stack{{}, GenTestStack()}
return orig
}
func GenTestProfilesDictionaryPtrSlice() []*ProfilesDictionary {
orig := make([]*ProfilesDictionary, 5)
orig[0] = NewProfilesDictionary()
orig[1] = GenTestProfilesDictionary()
orig[2] = NewProfilesDictionary()
orig[3] = GenTestProfilesDictionary()
orig[4] = NewProfilesDictionary()
return orig
}
func GenTestProfilesDictionarySlice() []ProfilesDictionary {
orig := make([]ProfilesDictionary, 5)
orig[1] = *GenTestProfilesDictionary()
orig[3] = *GenTestProfilesDictionary()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type ProfilesRequest struct {
RequestContext *RequestContext
ProfilesData ProfilesData
FormatVersion uint32
}
var (
protoPoolProfilesRequest = sync.Pool{
New: func() any {
return &ProfilesRequest{}
},
}
)
func NewProfilesRequest() *ProfilesRequest {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ProfilesRequest{}
}
return protoPoolProfilesRequest.Get().(*ProfilesRequest)
}
func DeleteProfilesRequest(orig *ProfilesRequest, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteRequestContext(orig.RequestContext, true)
DeleteProfilesData(&orig.ProfilesData, false)
orig.Reset()
if nullable {
protoPoolProfilesRequest.Put(orig)
}
}
func CopyProfilesRequest(dest, src *ProfilesRequest) *ProfilesRequest {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewProfilesRequest()
}
dest.RequestContext = CopyRequestContext(dest.RequestContext, src.RequestContext)
CopyProfilesData(&dest.ProfilesData, &src.ProfilesData)
dest.FormatVersion = src.FormatVersion
return dest
}
func CopyProfilesRequestSlice(dest, src []ProfilesRequest) []ProfilesRequest {
var newDest []ProfilesRequest
if cap(dest) < len(src) {
newDest = make([]ProfilesRequest, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteProfilesRequest(&dest[i], false)
}
}
for i := range src {
CopyProfilesRequest(&newDest[i], &src[i])
}
return newDest
}
func CopyProfilesRequestPtrSlice(dest, src []*ProfilesRequest) []*ProfilesRequest {
var newDest []*ProfilesRequest
if cap(dest) < len(src) {
newDest = make([]*ProfilesRequest, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewProfilesRequest()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteProfilesRequest(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewProfilesRequest()
}
}
for i := range src {
CopyProfilesRequest(newDest[i], src[i])
}
return newDest
}
func (orig *ProfilesRequest) Reset() {
*orig = ProfilesRequest{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ProfilesRequest) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.RequestContext != nil {
dest.WriteObjectField("requestContext")
orig.RequestContext.MarshalJSON(dest)
}
dest.WriteObjectField("profilesData")
orig.ProfilesData.MarshalJSON(dest)
if orig.FormatVersion != uint32(0) {
dest.WriteObjectField("formatVersion")
dest.WriteUint32(orig.FormatVersion)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ProfilesRequest) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "requestContext", "request_context":
orig.RequestContext = NewRequestContext()
orig.RequestContext.UnmarshalJSON(iter)
case "profilesData", "profiles_data":
orig.ProfilesData.UnmarshalJSON(iter)
case "formatVersion", "format_version":
orig.FormatVersion = iter.ReadUint32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ProfilesRequest) SizeProto() int {
var n int
var l int
_ = l
if orig.RequestContext != nil {
l = orig.RequestContext.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = orig.ProfilesData.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.FormatVersion != uint32(0) {
n += 5
}
return n
}
func (orig *ProfilesRequest) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.RequestContext != nil {
l = orig.RequestContext.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = orig.ProfilesData.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
if orig.FormatVersion != uint32(0) {
pos -= 4
binary.LittleEndian.PutUint32(buf[pos:], uint32(orig.FormatVersion))
pos--
buf[pos] = 0xd
}
return len(buf) - pos
}
func (orig *ProfilesRequest) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field RequestContext", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.RequestContext = NewRequestContext()
err = orig.RequestContext.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ProfilesData", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.ProfilesData.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 1:
if wireType != proto.WireTypeI32 {
return fmt.Errorf("proto: wrong wireType = %d for field FormatVersion", wireType)
}
var num uint32
num, pos, err = proto.ConsumeI32(buf, pos)
if err != nil {
return err
}
orig.FormatVersion = uint32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestProfilesRequest() *ProfilesRequest {
orig := NewProfilesRequest()
orig.RequestContext = GenTestRequestContext()
orig.ProfilesData = *GenTestProfilesData()
orig.FormatVersion = uint32(13)
return orig
}
func GenTestProfilesRequestPtrSlice() []*ProfilesRequest {
orig := make([]*ProfilesRequest, 5)
orig[0] = NewProfilesRequest()
orig[1] = GenTestProfilesRequest()
orig[2] = NewProfilesRequest()
orig[3] = GenTestProfilesRequest()
orig[4] = NewProfilesRequest()
return orig
}
func GenTestProfilesRequestSlice() []ProfilesRequest {
orig := make([]ProfilesRequest, 5)
orig[1] = *GenTestProfilesRequest()
orig[3] = *GenTestProfilesRequest()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
func (m *RequestContext) GetClientAddress() any {
if m != nil {
return m.ClientAddress
}
return nil
}
func (m *RequestContext) deleteClientAddress() {
if m == nil {
return
}
switch ov := m.ClientAddress.(type) {
case *RequestContext_IP:
deleteRequestContext_IP(ov)
case *RequestContext_TCP:
deleteRequestContext_TCP(ov)
case *RequestContext_UDP:
deleteRequestContext_UDP(ov)
case *RequestContext_Unix:
deleteRequestContext_Unix(ov)
}
m.ClientAddress = nil
}
var (
protoPoolRequestContext_IP = sync.Pool{
New: func() any {
return &RequestContext_IP{}
},
}
)
type RequestContext_IP struct {
IP *IPAddr
}
func NewRequestContext_IP() *RequestContext_IP {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &RequestContext_IP{}
}
return protoPoolRequestContext_IP.Get().(*RequestContext_IP)
}
func deleteRequestContext_IP(v *RequestContext_IP) {
// Called only when pool is enabled
v.IP = nil
protoPoolRequestContext_IP.Put(v)
}
func (m *RequestContext) GetIP() *IPAddr {
if v, ok := m.GetClientAddress().(*RequestContext_IP); ok {
return v.IP
}
return nil
}
var (
protoPoolRequestContext_TCP = sync.Pool{
New: func() any {
return &RequestContext_TCP{}
},
}
)
type RequestContext_TCP struct {
TCP *TCPAddr
}
func NewRequestContext_TCP() *RequestContext_TCP {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &RequestContext_TCP{}
}
return protoPoolRequestContext_TCP.Get().(*RequestContext_TCP)
}
func deleteRequestContext_TCP(v *RequestContext_TCP) {
// Called only when pool is enabled
v.TCP = nil
protoPoolRequestContext_TCP.Put(v)
}
func (m *RequestContext) GetTCP() *TCPAddr {
if v, ok := m.GetClientAddress().(*RequestContext_TCP); ok {
return v.TCP
}
return nil
}
var (
protoPoolRequestContext_UDP = sync.Pool{
New: func() any {
return &RequestContext_UDP{}
},
}
)
type RequestContext_UDP struct {
UDP *UDPAddr
}
func NewRequestContext_UDP() *RequestContext_UDP {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &RequestContext_UDP{}
}
return protoPoolRequestContext_UDP.Get().(*RequestContext_UDP)
}
func deleteRequestContext_UDP(v *RequestContext_UDP) {
// Called only when pool is enabled
v.UDP = nil
protoPoolRequestContext_UDP.Put(v)
}
func (m *RequestContext) GetUDP() *UDPAddr {
if v, ok := m.GetClientAddress().(*RequestContext_UDP); ok {
return v.UDP
}
return nil
}
var (
protoPoolRequestContext_Unix = sync.Pool{
New: func() any {
return &RequestContext_Unix{}
},
}
)
type RequestContext_Unix struct {
Unix *UnixAddr
}
func NewRequestContext_Unix() *RequestContext_Unix {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &RequestContext_Unix{}
}
return protoPoolRequestContext_Unix.Get().(*RequestContext_Unix)
}
func deleteRequestContext_Unix(v *RequestContext_Unix) {
// Called only when pool is enabled
v.Unix = nil
protoPoolRequestContext_Unix.Put(v)
}
func (m *RequestContext) GetUnix() *UnixAddr {
if v, ok := m.GetClientAddress().(*RequestContext_Unix); ok {
return v.Unix
}
return nil
}
type RequestContext struct {
ClientAddress any
SpanContext *SpanContext
ClientMetadata []KeyValue
}
var (
protoPoolRequestContext = sync.Pool{
New: func() any {
return &RequestContext{}
},
}
)
func NewRequestContext() *RequestContext {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &RequestContext{}
}
return protoPoolRequestContext.Get().(*RequestContext)
}
func DeleteRequestContext(orig *RequestContext, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteSpanContext(orig.SpanContext, true)
for i := range orig.ClientMetadata {
DeleteKeyValue(&orig.ClientMetadata[i], false)
}
orig.deleteClientAddress()
orig.Reset()
if nullable {
protoPoolRequestContext.Put(orig)
}
}
func CopyRequestContext(dest, src *RequestContext) *RequestContext {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewRequestContext()
}
dest.SpanContext = CopySpanContext(dest.SpanContext, src.SpanContext)
dest.ClientMetadata = CopyKeyValueSlice(dest.ClientMetadata, src.ClientMetadata)
switch t := src.ClientAddress.(type) {
case *RequestContext_IP:
ov := NewRequestContext_IP()
ov.IP = NewIPAddr()
CopyIPAddr(ov.IP, t.IP)
dest.ClientAddress = ov
case *RequestContext_TCP:
ov := NewRequestContext_TCP()
ov.TCP = NewTCPAddr()
CopyTCPAddr(ov.TCP, t.TCP)
dest.ClientAddress = ov
case *RequestContext_UDP:
ov := NewRequestContext_UDP()
ov.UDP = NewUDPAddr()
CopyUDPAddr(ov.UDP, t.UDP)
dest.ClientAddress = ov
case *RequestContext_Unix:
ov := NewRequestContext_Unix()
ov.Unix = NewUnixAddr()
CopyUnixAddr(ov.Unix, t.Unix)
dest.ClientAddress = ov
default:
dest.ClientAddress = nil
}
return dest
}
func CopyRequestContextSlice(dest, src []RequestContext) []RequestContext {
var newDest []RequestContext
if cap(dest) < len(src) {
newDest = make([]RequestContext, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteRequestContext(&dest[i], false)
}
}
for i := range src {
CopyRequestContext(&newDest[i], &src[i])
}
return newDest
}
func CopyRequestContextPtrSlice(dest, src []*RequestContext) []*RequestContext {
var newDest []*RequestContext
if cap(dest) < len(src) {
newDest = make([]*RequestContext, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewRequestContext()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteRequestContext(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewRequestContext()
}
}
for i := range src {
CopyRequestContext(newDest[i], src[i])
}
return newDest
}
func (orig *RequestContext) Reset() {
*orig = RequestContext{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *RequestContext) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.SpanContext != nil {
dest.WriteObjectField("spanContext")
orig.SpanContext.MarshalJSON(dest)
}
if len(orig.ClientMetadata) > 0 {
dest.WriteObjectField("clientMetadata")
dest.WriteArrayStart()
orig.ClientMetadata[0].MarshalJSON(dest)
for i := 1; i < len(orig.ClientMetadata); i++ {
dest.WriteMore()
orig.ClientMetadata[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
switch orig := orig.ClientAddress.(type) {
case *RequestContext_IP:
if orig.IP != nil {
dest.WriteObjectField("iP")
orig.IP.MarshalJSON(dest)
}
case *RequestContext_TCP:
if orig.TCP != nil {
dest.WriteObjectField("tCP")
orig.TCP.MarshalJSON(dest)
}
case *RequestContext_UDP:
if orig.UDP != nil {
dest.WriteObjectField("uDP")
orig.UDP.MarshalJSON(dest)
}
case *RequestContext_Unix:
if orig.Unix != nil {
dest.WriteObjectField("unix")
orig.Unix.MarshalJSON(dest)
}
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *RequestContext) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "spanContext", "span_context":
orig.SpanContext = NewSpanContext()
orig.SpanContext.UnmarshalJSON(iter)
case "clientMetadata", "client_metadata":
for iter.ReadArray() {
orig.ClientMetadata = append(orig.ClientMetadata, KeyValue{})
orig.ClientMetadata[len(orig.ClientMetadata)-1].UnmarshalJSON(iter)
}
case "iP":
{
ov := NewRequestContext_IP()
ov.IP = NewIPAddr()
ov.IP.UnmarshalJSON(iter)
orig.ClientAddress = ov
}
case "tCP":
{
ov := NewRequestContext_TCP()
ov.TCP = NewTCPAddr()
ov.TCP.UnmarshalJSON(iter)
orig.ClientAddress = ov
}
case "uDP":
{
ov := NewRequestContext_UDP()
ov.UDP = NewUDPAddr()
ov.UDP.UnmarshalJSON(iter)
orig.ClientAddress = ov
}
case "unix":
{
ov := NewRequestContext_Unix()
ov.Unix = NewUnixAddr()
ov.Unix.UnmarshalJSON(iter)
orig.ClientAddress = ov
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *RequestContext) SizeProto() int {
var n int
var l int
_ = l
if orig.SpanContext != nil {
l = orig.SpanContext.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.ClientMetadata {
l = orig.ClientMetadata[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
switch orig := orig.ClientAddress.(type) {
case nil:
_ = orig
break
case *RequestContext_IP:
if orig.IP != nil {
l = orig.IP.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
case *RequestContext_TCP:
if orig.TCP != nil {
l = orig.TCP.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
case *RequestContext_UDP:
if orig.UDP != nil {
l = orig.UDP.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
case *RequestContext_Unix:
if orig.Unix != nil {
l = orig.Unix.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
}
return n
}
func (orig *RequestContext) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.SpanContext != nil {
l = orig.SpanContext.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
for i := len(orig.ClientMetadata) - 1; i >= 0; i-- {
l = orig.ClientMetadata[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
switch orig := orig.ClientAddress.(type) {
case *RequestContext_IP:
if orig.IP != nil {
l = orig.IP.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
case *RequestContext_TCP:
if orig.TCP != nil {
l = orig.TCP.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x22
}
case *RequestContext_UDP:
if orig.UDP != nil {
l = orig.UDP.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x2a
}
case *RequestContext_Unix:
if orig.Unix != nil {
l = orig.Unix.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x32
}
}
return len(buf) - pos
}
func (orig *RequestContext) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SpanContext", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SpanContext = NewSpanContext()
err = orig.SpanContext.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ClientMetadata", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ClientMetadata = append(orig.ClientMetadata, KeyValue{})
err = orig.ClientMetadata[len(orig.ClientMetadata)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field IP", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewRequestContext_IP()
ov.IP = NewIPAddr()
err = ov.IP.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
orig.ClientAddress = ov
case 4:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TCP", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewRequestContext_TCP()
ov.TCP = NewTCPAddr()
err = ov.TCP.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
orig.ClientAddress = ov
case 5:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field UDP", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewRequestContext_UDP()
ov.UDP = NewUDPAddr()
err = ov.UDP.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
orig.ClientAddress = ov
case 6:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Unix", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
ov := NewRequestContext_Unix()
ov.Unix = NewUnixAddr()
err = ov.Unix.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
orig.ClientAddress = ov
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestRequestContext() *RequestContext {
orig := NewRequestContext()
orig.SpanContext = GenTestSpanContext()
orig.ClientMetadata = []KeyValue{{}, *GenTestKeyValue()}
orig.ClientAddress = &RequestContext_IP{IP: GenTestIPAddr()}
return orig
}
func GenTestRequestContextPtrSlice() []*RequestContext {
orig := make([]*RequestContext, 5)
orig[0] = NewRequestContext()
orig[1] = GenTestRequestContext()
orig[2] = NewRequestContext()
orig[3] = GenTestRequestContext()
orig[4] = NewRequestContext()
return orig
}
func GenTestRequestContextSlice() []RequestContext {
orig := make([]RequestContext, 5)
orig[1] = *GenTestRequestContext()
orig[3] = *GenTestRequestContext()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Resource is a message representing the resource information.
type Resource struct {
Attributes []KeyValue
EntityRefs []*EntityRef
DroppedAttributesCount uint32
}
var (
protoPoolResource = sync.Pool{
New: func() any {
return &Resource{}
},
}
)
func NewResource() *Resource {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Resource{}
}
return protoPoolResource.Get().(*Resource)
}
func DeleteResource(orig *Resource, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.Attributes {
DeleteKeyValue(&orig.Attributes[i], false)
}
for i := range orig.EntityRefs {
DeleteEntityRef(orig.EntityRefs[i], true)
}
orig.Reset()
if nullable {
protoPoolResource.Put(orig)
}
}
func CopyResource(dest, src *Resource) *Resource {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewResource()
}
dest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)
dest.DroppedAttributesCount = src.DroppedAttributesCount
dest.EntityRefs = CopyEntityRefPtrSlice(dest.EntityRefs, src.EntityRefs)
return dest
}
func CopyResourceSlice(dest, src []Resource) []Resource {
var newDest []Resource
if cap(dest) < len(src) {
newDest = make([]Resource, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteResource(&dest[i], false)
}
}
for i := range src {
CopyResource(&newDest[i], &src[i])
}
return newDest
}
func CopyResourcePtrSlice(dest, src []*Resource) []*Resource {
var newDest []*Resource
if cap(dest) < len(src) {
newDest = make([]*Resource, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewResource()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteResource(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewResource()
}
}
for i := range src {
CopyResource(newDest[i], src[i])
}
return newDest
}
func (orig *Resource) Reset() {
*orig = Resource{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Resource) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.Attributes) > 0 {
dest.WriteObjectField("attributes")
dest.WriteArrayStart()
orig.Attributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.Attributes); i++ {
dest.WriteMore()
orig.Attributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.DroppedAttributesCount != uint32(0) {
dest.WriteObjectField("droppedAttributesCount")
dest.WriteUint32(orig.DroppedAttributesCount)
}
if len(orig.EntityRefs) > 0 {
dest.WriteObjectField("entityRefs")
dest.WriteArrayStart()
orig.EntityRefs[0].MarshalJSON(dest)
for i := 1; i < len(orig.EntityRefs); i++ {
dest.WriteMore()
orig.EntityRefs[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Resource) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "attributes":
for iter.ReadArray() {
orig.Attributes = append(orig.Attributes, KeyValue{})
orig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)
}
case "droppedAttributesCount", "dropped_attributes_count":
orig.DroppedAttributesCount = iter.ReadUint32()
case "entityRefs", "entity_refs":
for iter.ReadArray() {
orig.EntityRefs = append(orig.EntityRefs, NewEntityRef())
orig.EntityRefs[len(orig.EntityRefs)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Resource) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.Attributes {
l = orig.Attributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.DroppedAttributesCount != uint32(0) {
n += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))
}
for i := range orig.EntityRefs {
l = orig.EntityRefs[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *Resource) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.Attributes) - 1; i >= 0; i-- {
l = orig.Attributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
if orig.DroppedAttributesCount != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))
pos--
buf[pos] = 0x10
}
for i := len(orig.EntityRefs) - 1; i >= 0; i-- {
l = orig.EntityRefs[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
return len(buf) - pos
}
func (orig *Resource) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Attributes = append(orig.Attributes, KeyValue{})
err = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field DroppedAttributesCount", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.DroppedAttributesCount = uint32(num)
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field EntityRefs", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.EntityRefs = append(orig.EntityRefs, NewEntityRef())
err = orig.EntityRefs[len(orig.EntityRefs)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestResource() *Resource {
orig := NewResource()
orig.Attributes = []KeyValue{{}, *GenTestKeyValue()}
orig.DroppedAttributesCount = uint32(13)
orig.EntityRefs = []*EntityRef{{}, GenTestEntityRef()}
return orig
}
func GenTestResourcePtrSlice() []*Resource {
orig := make([]*Resource, 5)
orig[0] = NewResource()
orig[1] = GenTestResource()
orig[2] = NewResource()
orig[3] = GenTestResource()
orig[4] = NewResource()
return orig
}
func GenTestResourceSlice() []Resource {
orig := make([]Resource, 5)
orig[1] = *GenTestResource()
orig[3] = *GenTestResource()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ResourceLogs is a collection of logs from a Resource.
type ResourceLogs struct {
Resource Resource
ScopeLogs []*ScopeLogs
SchemaUrl string
DeprecatedScopeLogs []*ScopeLogs
}
var (
protoPoolResourceLogs = sync.Pool{
New: func() any {
return &ResourceLogs{}
},
}
)
func NewResourceLogs() *ResourceLogs {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ResourceLogs{}
}
return protoPoolResourceLogs.Get().(*ResourceLogs)
}
func DeleteResourceLogs(orig *ResourceLogs, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteResource(&orig.Resource, false)
for i := range orig.ScopeLogs {
DeleteScopeLogs(orig.ScopeLogs[i], true)
}
for i := range orig.DeprecatedScopeLogs {
DeleteScopeLogs(orig.DeprecatedScopeLogs[i], true)
}
orig.Reset()
if nullable {
protoPoolResourceLogs.Put(orig)
}
}
func CopyResourceLogs(dest, src *ResourceLogs) *ResourceLogs {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewResourceLogs()
}
CopyResource(&dest.Resource, &src.Resource)
dest.ScopeLogs = CopyScopeLogsPtrSlice(dest.ScopeLogs, src.ScopeLogs)
dest.SchemaUrl = src.SchemaUrl
dest.DeprecatedScopeLogs = CopyScopeLogsPtrSlice(dest.DeprecatedScopeLogs, src.DeprecatedScopeLogs)
return dest
}
func CopyResourceLogsSlice(dest, src []ResourceLogs) []ResourceLogs {
var newDest []ResourceLogs
if cap(dest) < len(src) {
newDest = make([]ResourceLogs, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteResourceLogs(&dest[i], false)
}
}
for i := range src {
CopyResourceLogs(&newDest[i], &src[i])
}
return newDest
}
func CopyResourceLogsPtrSlice(dest, src []*ResourceLogs) []*ResourceLogs {
var newDest []*ResourceLogs
if cap(dest) < len(src) {
newDest = make([]*ResourceLogs, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewResourceLogs()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteResourceLogs(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewResourceLogs()
}
}
for i := range src {
CopyResourceLogs(newDest[i], src[i])
}
return newDest
}
func (orig *ResourceLogs) Reset() {
*orig = ResourceLogs{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ResourceLogs) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("resource")
orig.Resource.MarshalJSON(dest)
if len(orig.ScopeLogs) > 0 {
dest.WriteObjectField("scopeLogs")
dest.WriteArrayStart()
orig.ScopeLogs[0].MarshalJSON(dest)
for i := 1; i < len(orig.ScopeLogs); i++ {
dest.WriteMore()
orig.ScopeLogs[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.SchemaUrl != "" {
dest.WriteObjectField("schemaUrl")
dest.WriteString(orig.SchemaUrl)
}
if len(orig.DeprecatedScopeLogs) > 0 {
dest.WriteObjectField("deprecatedScopeLogs")
dest.WriteArrayStart()
orig.DeprecatedScopeLogs[0].MarshalJSON(dest)
for i := 1; i < len(orig.DeprecatedScopeLogs); i++ {
dest.WriteMore()
orig.DeprecatedScopeLogs[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ResourceLogs) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resource":
orig.Resource.UnmarshalJSON(iter)
case "scopeLogs", "scope_logs":
for iter.ReadArray() {
orig.ScopeLogs = append(orig.ScopeLogs, NewScopeLogs())
orig.ScopeLogs[len(orig.ScopeLogs)-1].UnmarshalJSON(iter)
}
case "schemaUrl", "schema_url":
orig.SchemaUrl = iter.ReadString()
case "deprecatedScopeLogs", "deprecated_scope_logs":
for iter.ReadArray() {
orig.DeprecatedScopeLogs = append(orig.DeprecatedScopeLogs, NewScopeLogs())
orig.DeprecatedScopeLogs[len(orig.DeprecatedScopeLogs)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ResourceLogs) SizeProto() int {
var n int
var l int
_ = l
l = orig.Resource.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
for i := range orig.ScopeLogs {
l = orig.ScopeLogs[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.SchemaUrl)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.DeprecatedScopeLogs {
l = orig.DeprecatedScopeLogs[i].SizeProto()
n += 2 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ResourceLogs) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.Resource.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
for i := len(orig.ScopeLogs) - 1; i >= 0; i-- {
l = orig.ScopeLogs[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = len(orig.SchemaUrl)
if l > 0 {
pos -= l
copy(buf[pos:], orig.SchemaUrl)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
for i := len(orig.DeprecatedScopeLogs) - 1; i >= 0; i-- {
l = orig.DeprecatedScopeLogs[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x3e
pos--
buf[pos] = 0xc2
}
return len(buf) - pos
}
func (orig *ResourceLogs) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Resource.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ScopeLogs", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ScopeLogs = append(orig.ScopeLogs, NewScopeLogs())
err = orig.ScopeLogs[len(orig.ScopeLogs)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SchemaUrl", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SchemaUrl = string(buf[startPos:pos])
case 1000:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field DeprecatedScopeLogs", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.DeprecatedScopeLogs = append(orig.DeprecatedScopeLogs, NewScopeLogs())
err = orig.DeprecatedScopeLogs[len(orig.DeprecatedScopeLogs)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestResourceLogs() *ResourceLogs {
orig := NewResourceLogs()
orig.Resource = *GenTestResource()
orig.ScopeLogs = []*ScopeLogs{{}, GenTestScopeLogs()}
orig.SchemaUrl = "test_schemaurl"
orig.DeprecatedScopeLogs = []*ScopeLogs{{}, GenTestScopeLogs()}
return orig
}
func GenTestResourceLogsPtrSlice() []*ResourceLogs {
orig := make([]*ResourceLogs, 5)
orig[0] = NewResourceLogs()
orig[1] = GenTestResourceLogs()
orig[2] = NewResourceLogs()
orig[3] = GenTestResourceLogs()
orig[4] = NewResourceLogs()
return orig
}
func GenTestResourceLogsSlice() []ResourceLogs {
orig := make([]ResourceLogs, 5)
orig[1] = *GenTestResourceLogs()
orig[3] = *GenTestResourceLogs()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ResourceMetrics is a collection of metrics from a Resource.
type ResourceMetrics struct {
Resource Resource
ScopeMetrics []*ScopeMetrics
SchemaUrl string
DeprecatedScopeMetrics []*ScopeMetrics
}
var (
protoPoolResourceMetrics = sync.Pool{
New: func() any {
return &ResourceMetrics{}
},
}
)
func NewResourceMetrics() *ResourceMetrics {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ResourceMetrics{}
}
return protoPoolResourceMetrics.Get().(*ResourceMetrics)
}
func DeleteResourceMetrics(orig *ResourceMetrics, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteResource(&orig.Resource, false)
for i := range orig.ScopeMetrics {
DeleteScopeMetrics(orig.ScopeMetrics[i], true)
}
for i := range orig.DeprecatedScopeMetrics {
DeleteScopeMetrics(orig.DeprecatedScopeMetrics[i], true)
}
orig.Reset()
if nullable {
protoPoolResourceMetrics.Put(orig)
}
}
func CopyResourceMetrics(dest, src *ResourceMetrics) *ResourceMetrics {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewResourceMetrics()
}
CopyResource(&dest.Resource, &src.Resource)
dest.ScopeMetrics = CopyScopeMetricsPtrSlice(dest.ScopeMetrics, src.ScopeMetrics)
dest.SchemaUrl = src.SchemaUrl
dest.DeprecatedScopeMetrics = CopyScopeMetricsPtrSlice(dest.DeprecatedScopeMetrics, src.DeprecatedScopeMetrics)
return dest
}
func CopyResourceMetricsSlice(dest, src []ResourceMetrics) []ResourceMetrics {
var newDest []ResourceMetrics
if cap(dest) < len(src) {
newDest = make([]ResourceMetrics, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteResourceMetrics(&dest[i], false)
}
}
for i := range src {
CopyResourceMetrics(&newDest[i], &src[i])
}
return newDest
}
func CopyResourceMetricsPtrSlice(dest, src []*ResourceMetrics) []*ResourceMetrics {
var newDest []*ResourceMetrics
if cap(dest) < len(src) {
newDest = make([]*ResourceMetrics, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewResourceMetrics()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteResourceMetrics(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewResourceMetrics()
}
}
for i := range src {
CopyResourceMetrics(newDest[i], src[i])
}
return newDest
}
func (orig *ResourceMetrics) Reset() {
*orig = ResourceMetrics{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ResourceMetrics) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("resource")
orig.Resource.MarshalJSON(dest)
if len(orig.ScopeMetrics) > 0 {
dest.WriteObjectField("scopeMetrics")
dest.WriteArrayStart()
orig.ScopeMetrics[0].MarshalJSON(dest)
for i := 1; i < len(orig.ScopeMetrics); i++ {
dest.WriteMore()
orig.ScopeMetrics[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.SchemaUrl != "" {
dest.WriteObjectField("schemaUrl")
dest.WriteString(orig.SchemaUrl)
}
if len(orig.DeprecatedScopeMetrics) > 0 {
dest.WriteObjectField("deprecatedScopeMetrics")
dest.WriteArrayStart()
orig.DeprecatedScopeMetrics[0].MarshalJSON(dest)
for i := 1; i < len(orig.DeprecatedScopeMetrics); i++ {
dest.WriteMore()
orig.DeprecatedScopeMetrics[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ResourceMetrics) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resource":
orig.Resource.UnmarshalJSON(iter)
case "scopeMetrics", "scope_metrics":
for iter.ReadArray() {
orig.ScopeMetrics = append(orig.ScopeMetrics, NewScopeMetrics())
orig.ScopeMetrics[len(orig.ScopeMetrics)-1].UnmarshalJSON(iter)
}
case "schemaUrl", "schema_url":
orig.SchemaUrl = iter.ReadString()
case "deprecatedScopeMetrics", "deprecated_scope_metrics":
for iter.ReadArray() {
orig.DeprecatedScopeMetrics = append(orig.DeprecatedScopeMetrics, NewScopeMetrics())
orig.DeprecatedScopeMetrics[len(orig.DeprecatedScopeMetrics)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ResourceMetrics) SizeProto() int {
var n int
var l int
_ = l
l = orig.Resource.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
for i := range orig.ScopeMetrics {
l = orig.ScopeMetrics[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.SchemaUrl)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.DeprecatedScopeMetrics {
l = orig.DeprecatedScopeMetrics[i].SizeProto()
n += 2 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ResourceMetrics) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.Resource.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
for i := len(orig.ScopeMetrics) - 1; i >= 0; i-- {
l = orig.ScopeMetrics[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = len(orig.SchemaUrl)
if l > 0 {
pos -= l
copy(buf[pos:], orig.SchemaUrl)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
for i := len(orig.DeprecatedScopeMetrics) - 1; i >= 0; i-- {
l = orig.DeprecatedScopeMetrics[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x3e
pos--
buf[pos] = 0xc2
}
return len(buf) - pos
}
func (orig *ResourceMetrics) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Resource.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ScopeMetrics", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ScopeMetrics = append(orig.ScopeMetrics, NewScopeMetrics())
err = orig.ScopeMetrics[len(orig.ScopeMetrics)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SchemaUrl", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SchemaUrl = string(buf[startPos:pos])
case 1000:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field DeprecatedScopeMetrics", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.DeprecatedScopeMetrics = append(orig.DeprecatedScopeMetrics, NewScopeMetrics())
err = orig.DeprecatedScopeMetrics[len(orig.DeprecatedScopeMetrics)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestResourceMetrics() *ResourceMetrics {
orig := NewResourceMetrics()
orig.Resource = *GenTestResource()
orig.ScopeMetrics = []*ScopeMetrics{{}, GenTestScopeMetrics()}
orig.SchemaUrl = "test_schemaurl"
orig.DeprecatedScopeMetrics = []*ScopeMetrics{{}, GenTestScopeMetrics()}
return orig
}
func GenTestResourceMetricsPtrSlice() []*ResourceMetrics {
orig := make([]*ResourceMetrics, 5)
orig[0] = NewResourceMetrics()
orig[1] = GenTestResourceMetrics()
orig[2] = NewResourceMetrics()
orig[3] = GenTestResourceMetrics()
orig[4] = NewResourceMetrics()
return orig
}
func GenTestResourceMetricsSlice() []ResourceMetrics {
orig := make([]ResourceMetrics, 5)
orig[1] = *GenTestResourceMetrics()
orig[3] = *GenTestResourceMetrics()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ResourceProfiles is a collection of profiles from a Resource.
type ResourceProfiles struct {
SchemaUrl string
Resource Resource
ScopeProfiles []*ScopeProfiles
}
var (
protoPoolResourceProfiles = sync.Pool{
New: func() any {
return &ResourceProfiles{}
},
}
)
func NewResourceProfiles() *ResourceProfiles {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ResourceProfiles{}
}
return protoPoolResourceProfiles.Get().(*ResourceProfiles)
}
func DeleteResourceProfiles(orig *ResourceProfiles, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteResource(&orig.Resource, false)
for i := range orig.ScopeProfiles {
DeleteScopeProfiles(orig.ScopeProfiles[i], true)
}
orig.Reset()
if nullable {
protoPoolResourceProfiles.Put(orig)
}
}
func CopyResourceProfiles(dest, src *ResourceProfiles) *ResourceProfiles {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewResourceProfiles()
}
CopyResource(&dest.Resource, &src.Resource)
dest.ScopeProfiles = CopyScopeProfilesPtrSlice(dest.ScopeProfiles, src.ScopeProfiles)
dest.SchemaUrl = src.SchemaUrl
return dest
}
func CopyResourceProfilesSlice(dest, src []ResourceProfiles) []ResourceProfiles {
var newDest []ResourceProfiles
if cap(dest) < len(src) {
newDest = make([]ResourceProfiles, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteResourceProfiles(&dest[i], false)
}
}
for i := range src {
CopyResourceProfiles(&newDest[i], &src[i])
}
return newDest
}
func CopyResourceProfilesPtrSlice(dest, src []*ResourceProfiles) []*ResourceProfiles {
var newDest []*ResourceProfiles
if cap(dest) < len(src) {
newDest = make([]*ResourceProfiles, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewResourceProfiles()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteResourceProfiles(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewResourceProfiles()
}
}
for i := range src {
CopyResourceProfiles(newDest[i], src[i])
}
return newDest
}
func (orig *ResourceProfiles) Reset() {
*orig = ResourceProfiles{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ResourceProfiles) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("resource")
orig.Resource.MarshalJSON(dest)
if len(orig.ScopeProfiles) > 0 {
dest.WriteObjectField("scopeProfiles")
dest.WriteArrayStart()
orig.ScopeProfiles[0].MarshalJSON(dest)
for i := 1; i < len(orig.ScopeProfiles); i++ {
dest.WriteMore()
orig.ScopeProfiles[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.SchemaUrl != "" {
dest.WriteObjectField("schemaUrl")
dest.WriteString(orig.SchemaUrl)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ResourceProfiles) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resource":
orig.Resource.UnmarshalJSON(iter)
case "scopeProfiles", "scope_profiles":
for iter.ReadArray() {
orig.ScopeProfiles = append(orig.ScopeProfiles, NewScopeProfiles())
orig.ScopeProfiles[len(orig.ScopeProfiles)-1].UnmarshalJSON(iter)
}
case "schemaUrl", "schema_url":
orig.SchemaUrl = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ResourceProfiles) SizeProto() int {
var n int
var l int
_ = l
l = orig.Resource.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
for i := range orig.ScopeProfiles {
l = orig.ScopeProfiles[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.SchemaUrl)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ResourceProfiles) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.Resource.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
for i := len(orig.ScopeProfiles) - 1; i >= 0; i-- {
l = orig.ScopeProfiles[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = len(orig.SchemaUrl)
if l > 0 {
pos -= l
copy(buf[pos:], orig.SchemaUrl)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
return len(buf) - pos
}
func (orig *ResourceProfiles) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Resource.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ScopeProfiles", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ScopeProfiles = append(orig.ScopeProfiles, NewScopeProfiles())
err = orig.ScopeProfiles[len(orig.ScopeProfiles)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SchemaUrl", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SchemaUrl = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestResourceProfiles() *ResourceProfiles {
orig := NewResourceProfiles()
orig.Resource = *GenTestResource()
orig.ScopeProfiles = []*ScopeProfiles{{}, GenTestScopeProfiles()}
orig.SchemaUrl = "test_schemaurl"
return orig
}
func GenTestResourceProfilesPtrSlice() []*ResourceProfiles {
orig := make([]*ResourceProfiles, 5)
orig[0] = NewResourceProfiles()
orig[1] = GenTestResourceProfiles()
orig[2] = NewResourceProfiles()
orig[3] = GenTestResourceProfiles()
orig[4] = NewResourceProfiles()
return orig
}
func GenTestResourceProfilesSlice() []ResourceProfiles {
orig := make([]ResourceProfiles, 5)
orig[1] = *GenTestResourceProfiles()
orig[3] = *GenTestResourceProfiles()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ResourceSpans is a collection of spans from a Resource.
type ResourceSpans struct {
Resource Resource
ScopeSpans []*ScopeSpans
SchemaUrl string
DeprecatedScopeSpans []*ScopeSpans
}
var (
protoPoolResourceSpans = sync.Pool{
New: func() any {
return &ResourceSpans{}
},
}
)
func NewResourceSpans() *ResourceSpans {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ResourceSpans{}
}
return protoPoolResourceSpans.Get().(*ResourceSpans)
}
func DeleteResourceSpans(orig *ResourceSpans, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteResource(&orig.Resource, false)
for i := range orig.ScopeSpans {
DeleteScopeSpans(orig.ScopeSpans[i], true)
}
for i := range orig.DeprecatedScopeSpans {
DeleteScopeSpans(orig.DeprecatedScopeSpans[i], true)
}
orig.Reset()
if nullable {
protoPoolResourceSpans.Put(orig)
}
}
func CopyResourceSpans(dest, src *ResourceSpans) *ResourceSpans {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewResourceSpans()
}
CopyResource(&dest.Resource, &src.Resource)
dest.ScopeSpans = CopyScopeSpansPtrSlice(dest.ScopeSpans, src.ScopeSpans)
dest.SchemaUrl = src.SchemaUrl
dest.DeprecatedScopeSpans = CopyScopeSpansPtrSlice(dest.DeprecatedScopeSpans, src.DeprecatedScopeSpans)
return dest
}
func CopyResourceSpansSlice(dest, src []ResourceSpans) []ResourceSpans {
var newDest []ResourceSpans
if cap(dest) < len(src) {
newDest = make([]ResourceSpans, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteResourceSpans(&dest[i], false)
}
}
for i := range src {
CopyResourceSpans(&newDest[i], &src[i])
}
return newDest
}
func CopyResourceSpansPtrSlice(dest, src []*ResourceSpans) []*ResourceSpans {
var newDest []*ResourceSpans
if cap(dest) < len(src) {
newDest = make([]*ResourceSpans, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewResourceSpans()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteResourceSpans(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewResourceSpans()
}
}
for i := range src {
CopyResourceSpans(newDest[i], src[i])
}
return newDest
}
func (orig *ResourceSpans) Reset() {
*orig = ResourceSpans{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ResourceSpans) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("resource")
orig.Resource.MarshalJSON(dest)
if len(orig.ScopeSpans) > 0 {
dest.WriteObjectField("scopeSpans")
dest.WriteArrayStart()
orig.ScopeSpans[0].MarshalJSON(dest)
for i := 1; i < len(orig.ScopeSpans); i++ {
dest.WriteMore()
orig.ScopeSpans[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.SchemaUrl != "" {
dest.WriteObjectField("schemaUrl")
dest.WriteString(orig.SchemaUrl)
}
if len(orig.DeprecatedScopeSpans) > 0 {
dest.WriteObjectField("deprecatedScopeSpans")
dest.WriteArrayStart()
orig.DeprecatedScopeSpans[0].MarshalJSON(dest)
for i := 1; i < len(orig.DeprecatedScopeSpans); i++ {
dest.WriteMore()
orig.DeprecatedScopeSpans[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ResourceSpans) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resource":
orig.Resource.UnmarshalJSON(iter)
case "scopeSpans", "scope_spans":
for iter.ReadArray() {
orig.ScopeSpans = append(orig.ScopeSpans, NewScopeSpans())
orig.ScopeSpans[len(orig.ScopeSpans)-1].UnmarshalJSON(iter)
}
case "schemaUrl", "schema_url":
orig.SchemaUrl = iter.ReadString()
case "deprecatedScopeSpans", "deprecated_scope_spans":
for iter.ReadArray() {
orig.DeprecatedScopeSpans = append(orig.DeprecatedScopeSpans, NewScopeSpans())
orig.DeprecatedScopeSpans[len(orig.DeprecatedScopeSpans)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ResourceSpans) SizeProto() int {
var n int
var l int
_ = l
l = orig.Resource.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
for i := range orig.ScopeSpans {
l = orig.ScopeSpans[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.SchemaUrl)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.DeprecatedScopeSpans {
l = orig.DeprecatedScopeSpans[i].SizeProto()
n += 2 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ResourceSpans) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.Resource.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
for i := len(orig.ScopeSpans) - 1; i >= 0; i-- {
l = orig.ScopeSpans[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = len(orig.SchemaUrl)
if l > 0 {
pos -= l
copy(buf[pos:], orig.SchemaUrl)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
for i := len(orig.DeprecatedScopeSpans) - 1; i >= 0; i-- {
l = orig.DeprecatedScopeSpans[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x3e
pos--
buf[pos] = 0xc2
}
return len(buf) - pos
}
func (orig *ResourceSpans) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Resource.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ScopeSpans", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ScopeSpans = append(orig.ScopeSpans, NewScopeSpans())
err = orig.ScopeSpans[len(orig.ScopeSpans)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SchemaUrl", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SchemaUrl = string(buf[startPos:pos])
case 1000:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field DeprecatedScopeSpans", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.DeprecatedScopeSpans = append(orig.DeprecatedScopeSpans, NewScopeSpans())
err = orig.DeprecatedScopeSpans[len(orig.DeprecatedScopeSpans)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestResourceSpans() *ResourceSpans {
orig := NewResourceSpans()
orig.Resource = *GenTestResource()
orig.ScopeSpans = []*ScopeSpans{{}, GenTestScopeSpans()}
orig.SchemaUrl = "test_schemaurl"
orig.DeprecatedScopeSpans = []*ScopeSpans{{}, GenTestScopeSpans()}
return orig
}
func GenTestResourceSpansPtrSlice() []*ResourceSpans {
orig := make([]*ResourceSpans, 5)
orig[0] = NewResourceSpans()
orig[1] = GenTestResourceSpans()
orig[2] = NewResourceSpans()
orig[3] = GenTestResourceSpans()
orig[4] = NewResourceSpans()
return orig
}
func GenTestResourceSpansSlice() []ResourceSpans {
orig := make([]ResourceSpans, 5)
orig[1] = *GenTestResourceSpans()
orig[3] = *GenTestResourceSpans()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Sample represents each record value encountered within a profiled program.
type Sample struct {
AttributeIndices []int32
Values []int64
TimestampsUnixNano []uint64
StackIndex int32
LinkIndex int32
}
var (
protoPoolSample = sync.Pool{
New: func() any {
return &Sample{}
},
}
)
func NewSample() *Sample {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Sample{}
}
return protoPoolSample.Get().(*Sample)
}
func DeleteSample(orig *Sample, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolSample.Put(orig)
}
}
func CopySample(dest, src *Sample) *Sample {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewSample()
}
dest.StackIndex = src.StackIndex
dest.AttributeIndices = append(dest.AttributeIndices[:0], src.AttributeIndices...)
dest.LinkIndex = src.LinkIndex
dest.Values = append(dest.Values[:0], src.Values...)
dest.TimestampsUnixNano = append(dest.TimestampsUnixNano[:0], src.TimestampsUnixNano...)
return dest
}
func CopySampleSlice(dest, src []Sample) []Sample {
var newDest []Sample
if cap(dest) < len(src) {
newDest = make([]Sample, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSample(&dest[i], false)
}
}
for i := range src {
CopySample(&newDest[i], &src[i])
}
return newDest
}
func CopySamplePtrSlice(dest, src []*Sample) []*Sample {
var newDest []*Sample
if cap(dest) < len(src) {
newDest = make([]*Sample, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSample()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSample(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSample()
}
}
for i := range src {
CopySample(newDest[i], src[i])
}
return newDest
}
func (orig *Sample) Reset() {
*orig = Sample{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Sample) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.StackIndex != int32(0) {
dest.WriteObjectField("stackIndex")
dest.WriteInt32(orig.StackIndex)
}
if len(orig.AttributeIndices) > 0 {
dest.WriteObjectField("attributeIndices")
dest.WriteArrayStart()
dest.WriteInt32(orig.AttributeIndices[0])
for i := 1; i < len(orig.AttributeIndices); i++ {
dest.WriteMore()
dest.WriteInt32(orig.AttributeIndices[i])
}
dest.WriteArrayEnd()
}
if orig.LinkIndex != int32(0) {
dest.WriteObjectField("linkIndex")
dest.WriteInt32(orig.LinkIndex)
}
if len(orig.Values) > 0 {
dest.WriteObjectField("values")
dest.WriteArrayStart()
dest.WriteInt64(orig.Values[0])
for i := 1; i < len(orig.Values); i++ {
dest.WriteMore()
dest.WriteInt64(orig.Values[i])
}
dest.WriteArrayEnd()
}
if len(orig.TimestampsUnixNano) > 0 {
dest.WriteObjectField("timestampsUnixNano")
dest.WriteArrayStart()
dest.WriteUint64(orig.TimestampsUnixNano[0])
for i := 1; i < len(orig.TimestampsUnixNano); i++ {
dest.WriteMore()
dest.WriteUint64(orig.TimestampsUnixNano[i])
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Sample) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "stackIndex", "stack_index":
orig.StackIndex = iter.ReadInt32()
case "attributeIndices", "attribute_indices":
for iter.ReadArray() {
orig.AttributeIndices = append(orig.AttributeIndices, iter.ReadInt32())
}
case "linkIndex", "link_index":
orig.LinkIndex = iter.ReadInt32()
case "values":
for iter.ReadArray() {
orig.Values = append(orig.Values, iter.ReadInt64())
}
case "timestampsUnixNano", "timestamps_unix_nano":
for iter.ReadArray() {
orig.TimestampsUnixNano = append(orig.TimestampsUnixNano, iter.ReadUint64())
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Sample) SizeProto() int {
var n int
var l int
_ = l
if orig.StackIndex != int32(0) {
n += 1 + proto.Sov(uint64(orig.StackIndex))
}
if len(orig.AttributeIndices) > 0 {
l = 0
for _, e := range orig.AttributeIndices {
l += proto.Sov(uint64(e))
}
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.LinkIndex != int32(0) {
n += 1 + proto.Sov(uint64(orig.LinkIndex))
}
if len(orig.Values) > 0 {
l = 0
for _, e := range orig.Values {
l += proto.Sov(uint64(e))
}
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.TimestampsUnixNano)
if l > 0 {
l *= 8
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *Sample) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.StackIndex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.StackIndex))
pos--
buf[pos] = 0x8
}
l = len(orig.AttributeIndices)
if l > 0 {
endPos := pos
for i := l - 1; i >= 0; i-- {
pos = proto.EncodeVarint(buf, pos, uint64(orig.AttributeIndices[i]))
}
pos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))
pos--
buf[pos] = 0x12
}
if orig.LinkIndex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.LinkIndex))
pos--
buf[pos] = 0x18
}
l = len(orig.Values)
if l > 0 {
endPos := pos
for i := l - 1; i >= 0; i-- {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Values[i]))
}
pos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))
pos--
buf[pos] = 0x22
}
l = len(orig.TimestampsUnixNano)
if l > 0 {
for i := l - 1; i >= 0; i-- {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimestampsUnixNano[i]))
}
pos = proto.EncodeVarint(buf, pos, uint64(l*8))
pos--
buf[pos] = 0x2a
}
return len(buf) - pos
}
func (orig *Sample) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field StackIndex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.StackIndex = int32(num)
case 2:
switch wireType {
case proto.WireTypeLen:
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
var num uint64
for startPos < pos {
num, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)
if err != nil {
return err
}
orig.AttributeIndices = append(orig.AttributeIndices, int32(num))
}
if startPos != pos {
return fmt.Errorf("proto: invalid field len = %d for field AttributeIndices", pos-startPos)
}
case proto.WireTypeVarint:
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.AttributeIndices = append(orig.AttributeIndices, int32(num))
default:
return fmt.Errorf("proto: wrong wireType = %d for field AttributeIndices", wireType)
}
case 3:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field LinkIndex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.LinkIndex = int32(num)
case 4:
switch wireType {
case proto.WireTypeLen:
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
var num uint64
for startPos < pos {
num, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)
if err != nil {
return err
}
orig.Values = append(orig.Values, int64(num))
}
if startPos != pos {
return fmt.Errorf("proto: invalid field len = %d for field Values", pos-startPos)
}
case proto.WireTypeVarint:
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Values = append(orig.Values, int64(num))
default:
return fmt.Errorf("proto: wrong wireType = %d for field Values", wireType)
}
case 5:
switch wireType {
case proto.WireTypeLen:
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
size := length / 8
orig.TimestampsUnixNano = make([]uint64, size)
var num uint64
for i := 0; i < size; i++ {
num, startPos, err = proto.ConsumeI64(buf[:pos], startPos)
if err != nil {
return err
}
orig.TimestampsUnixNano[i] = uint64(num)
}
if startPos != pos {
return fmt.Errorf("proto: invalid field len = %d for field TimestampsUnixNano", pos-startPos)
}
case proto.WireTypeI64:
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.TimestampsUnixNano = append(orig.TimestampsUnixNano, uint64(num))
default:
return fmt.Errorf("proto: wrong wireType = %d for field TimestampsUnixNano", wireType)
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestSample() *Sample {
orig := NewSample()
orig.StackIndex = int32(13)
orig.AttributeIndices = []int32{int32(0), int32(13)}
orig.LinkIndex = int32(13)
orig.Values = []int64{int64(0), int64(13)}
orig.TimestampsUnixNano = []uint64{uint64(0), uint64(13)}
return orig
}
func GenTestSamplePtrSlice() []*Sample {
orig := make([]*Sample, 5)
orig[0] = NewSample()
orig[1] = GenTestSample()
orig[2] = NewSample()
orig[3] = GenTestSample()
orig[4] = NewSample()
return orig
}
func GenTestSampleSlice() []Sample {
orig := make([]Sample, 5)
orig[1] = *GenTestSample()
orig[3] = *GenTestSample()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ScopeLogs is a collection of logs from a LibraryInstrumentation.
type ScopeLogs struct {
SchemaUrl string
LogRecords []*LogRecord
Scope InstrumentationScope
}
var (
protoPoolScopeLogs = sync.Pool{
New: func() any {
return &ScopeLogs{}
},
}
)
func NewScopeLogs() *ScopeLogs {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ScopeLogs{}
}
return protoPoolScopeLogs.Get().(*ScopeLogs)
}
func DeleteScopeLogs(orig *ScopeLogs, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteInstrumentationScope(&orig.Scope, false)
for i := range orig.LogRecords {
DeleteLogRecord(orig.LogRecords[i], true)
}
orig.Reset()
if nullable {
protoPoolScopeLogs.Put(orig)
}
}
func CopyScopeLogs(dest, src *ScopeLogs) *ScopeLogs {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewScopeLogs()
}
CopyInstrumentationScope(&dest.Scope, &src.Scope)
dest.LogRecords = CopyLogRecordPtrSlice(dest.LogRecords, src.LogRecords)
dest.SchemaUrl = src.SchemaUrl
return dest
}
func CopyScopeLogsSlice(dest, src []ScopeLogs) []ScopeLogs {
var newDest []ScopeLogs
if cap(dest) < len(src) {
newDest = make([]ScopeLogs, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteScopeLogs(&dest[i], false)
}
}
for i := range src {
CopyScopeLogs(&newDest[i], &src[i])
}
return newDest
}
func CopyScopeLogsPtrSlice(dest, src []*ScopeLogs) []*ScopeLogs {
var newDest []*ScopeLogs
if cap(dest) < len(src) {
newDest = make([]*ScopeLogs, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewScopeLogs()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteScopeLogs(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewScopeLogs()
}
}
for i := range src {
CopyScopeLogs(newDest[i], src[i])
}
return newDest
}
func (orig *ScopeLogs) Reset() {
*orig = ScopeLogs{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ScopeLogs) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("scope")
orig.Scope.MarshalJSON(dest)
if len(orig.LogRecords) > 0 {
dest.WriteObjectField("logRecords")
dest.WriteArrayStart()
orig.LogRecords[0].MarshalJSON(dest)
for i := 1; i < len(orig.LogRecords); i++ {
dest.WriteMore()
orig.LogRecords[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.SchemaUrl != "" {
dest.WriteObjectField("schemaUrl")
dest.WriteString(orig.SchemaUrl)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ScopeLogs) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "scope":
orig.Scope.UnmarshalJSON(iter)
case "logRecords", "log_records":
for iter.ReadArray() {
orig.LogRecords = append(orig.LogRecords, NewLogRecord())
orig.LogRecords[len(orig.LogRecords)-1].UnmarshalJSON(iter)
}
case "schemaUrl", "schema_url":
orig.SchemaUrl = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ScopeLogs) SizeProto() int {
var n int
var l int
_ = l
l = orig.Scope.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
for i := range orig.LogRecords {
l = orig.LogRecords[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.SchemaUrl)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ScopeLogs) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.Scope.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
for i := len(orig.LogRecords) - 1; i >= 0; i-- {
l = orig.LogRecords[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = len(orig.SchemaUrl)
if l > 0 {
pos -= l
copy(buf[pos:], orig.SchemaUrl)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
return len(buf) - pos
}
func (orig *ScopeLogs) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Scope", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Scope.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field LogRecords", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.LogRecords = append(orig.LogRecords, NewLogRecord())
err = orig.LogRecords[len(orig.LogRecords)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SchemaUrl", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SchemaUrl = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestScopeLogs() *ScopeLogs {
orig := NewScopeLogs()
orig.Scope = *GenTestInstrumentationScope()
orig.LogRecords = []*LogRecord{{}, GenTestLogRecord()}
orig.SchemaUrl = "test_schemaurl"
return orig
}
func GenTestScopeLogsPtrSlice() []*ScopeLogs {
orig := make([]*ScopeLogs, 5)
orig[0] = NewScopeLogs()
orig[1] = GenTestScopeLogs()
orig[2] = NewScopeLogs()
orig[3] = GenTestScopeLogs()
orig[4] = NewScopeLogs()
return orig
}
func GenTestScopeLogsSlice() []ScopeLogs {
orig := make([]ScopeLogs, 5)
orig[1] = *GenTestScopeLogs()
orig[3] = *GenTestScopeLogs()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ScopeMetrics is a collection of metrics from a LibraryInstrumentation.
type ScopeMetrics struct {
SchemaUrl string
Metrics []*Metric
Scope InstrumentationScope
}
var (
protoPoolScopeMetrics = sync.Pool{
New: func() any {
return &ScopeMetrics{}
},
}
)
func NewScopeMetrics() *ScopeMetrics {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ScopeMetrics{}
}
return protoPoolScopeMetrics.Get().(*ScopeMetrics)
}
func DeleteScopeMetrics(orig *ScopeMetrics, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteInstrumentationScope(&orig.Scope, false)
for i := range orig.Metrics {
DeleteMetric(orig.Metrics[i], true)
}
orig.Reset()
if nullable {
protoPoolScopeMetrics.Put(orig)
}
}
func CopyScopeMetrics(dest, src *ScopeMetrics) *ScopeMetrics {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewScopeMetrics()
}
CopyInstrumentationScope(&dest.Scope, &src.Scope)
dest.Metrics = CopyMetricPtrSlice(dest.Metrics, src.Metrics)
dest.SchemaUrl = src.SchemaUrl
return dest
}
func CopyScopeMetricsSlice(dest, src []ScopeMetrics) []ScopeMetrics {
var newDest []ScopeMetrics
if cap(dest) < len(src) {
newDest = make([]ScopeMetrics, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteScopeMetrics(&dest[i], false)
}
}
for i := range src {
CopyScopeMetrics(&newDest[i], &src[i])
}
return newDest
}
func CopyScopeMetricsPtrSlice(dest, src []*ScopeMetrics) []*ScopeMetrics {
var newDest []*ScopeMetrics
if cap(dest) < len(src) {
newDest = make([]*ScopeMetrics, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewScopeMetrics()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteScopeMetrics(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewScopeMetrics()
}
}
for i := range src {
CopyScopeMetrics(newDest[i], src[i])
}
return newDest
}
func (orig *ScopeMetrics) Reset() {
*orig = ScopeMetrics{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ScopeMetrics) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("scope")
orig.Scope.MarshalJSON(dest)
if len(orig.Metrics) > 0 {
dest.WriteObjectField("metrics")
dest.WriteArrayStart()
orig.Metrics[0].MarshalJSON(dest)
for i := 1; i < len(orig.Metrics); i++ {
dest.WriteMore()
orig.Metrics[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.SchemaUrl != "" {
dest.WriteObjectField("schemaUrl")
dest.WriteString(orig.SchemaUrl)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ScopeMetrics) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "scope":
orig.Scope.UnmarshalJSON(iter)
case "metrics":
for iter.ReadArray() {
orig.Metrics = append(orig.Metrics, NewMetric())
orig.Metrics[len(orig.Metrics)-1].UnmarshalJSON(iter)
}
case "schemaUrl", "schema_url":
orig.SchemaUrl = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ScopeMetrics) SizeProto() int {
var n int
var l int
_ = l
l = orig.Scope.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
for i := range orig.Metrics {
l = orig.Metrics[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.SchemaUrl)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ScopeMetrics) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.Scope.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
for i := len(orig.Metrics) - 1; i >= 0; i-- {
l = orig.Metrics[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = len(orig.SchemaUrl)
if l > 0 {
pos -= l
copy(buf[pos:], orig.SchemaUrl)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
return len(buf) - pos
}
func (orig *ScopeMetrics) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Scope", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Scope.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Metrics", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Metrics = append(orig.Metrics, NewMetric())
err = orig.Metrics[len(orig.Metrics)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SchemaUrl", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SchemaUrl = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestScopeMetrics() *ScopeMetrics {
orig := NewScopeMetrics()
orig.Scope = *GenTestInstrumentationScope()
orig.Metrics = []*Metric{{}, GenTestMetric()}
orig.SchemaUrl = "test_schemaurl"
return orig
}
func GenTestScopeMetricsPtrSlice() []*ScopeMetrics {
orig := make([]*ScopeMetrics, 5)
orig[0] = NewScopeMetrics()
orig[1] = GenTestScopeMetrics()
orig[2] = NewScopeMetrics()
orig[3] = GenTestScopeMetrics()
orig[4] = NewScopeMetrics()
return orig
}
func GenTestScopeMetricsSlice() []ScopeMetrics {
orig := make([]ScopeMetrics, 5)
orig[1] = *GenTestScopeMetrics()
orig[3] = *GenTestScopeMetrics()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ScopeProfiles is a collection of profiles from a LibraryInstrumentation.
type ScopeProfiles struct {
SchemaUrl string
Profiles []*Profile
Scope InstrumentationScope
}
var (
protoPoolScopeProfiles = sync.Pool{
New: func() any {
return &ScopeProfiles{}
},
}
)
func NewScopeProfiles() *ScopeProfiles {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ScopeProfiles{}
}
return protoPoolScopeProfiles.Get().(*ScopeProfiles)
}
func DeleteScopeProfiles(orig *ScopeProfiles, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteInstrumentationScope(&orig.Scope, false)
for i := range orig.Profiles {
DeleteProfile(orig.Profiles[i], true)
}
orig.Reset()
if nullable {
protoPoolScopeProfiles.Put(orig)
}
}
func CopyScopeProfiles(dest, src *ScopeProfiles) *ScopeProfiles {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewScopeProfiles()
}
CopyInstrumentationScope(&dest.Scope, &src.Scope)
dest.Profiles = CopyProfilePtrSlice(dest.Profiles, src.Profiles)
dest.SchemaUrl = src.SchemaUrl
return dest
}
func CopyScopeProfilesSlice(dest, src []ScopeProfiles) []ScopeProfiles {
var newDest []ScopeProfiles
if cap(dest) < len(src) {
newDest = make([]ScopeProfiles, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteScopeProfiles(&dest[i], false)
}
}
for i := range src {
CopyScopeProfiles(&newDest[i], &src[i])
}
return newDest
}
func CopyScopeProfilesPtrSlice(dest, src []*ScopeProfiles) []*ScopeProfiles {
var newDest []*ScopeProfiles
if cap(dest) < len(src) {
newDest = make([]*ScopeProfiles, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewScopeProfiles()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteScopeProfiles(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewScopeProfiles()
}
}
for i := range src {
CopyScopeProfiles(newDest[i], src[i])
}
return newDest
}
func (orig *ScopeProfiles) Reset() {
*orig = ScopeProfiles{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ScopeProfiles) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("scope")
orig.Scope.MarshalJSON(dest)
if len(orig.Profiles) > 0 {
dest.WriteObjectField("profiles")
dest.WriteArrayStart()
orig.Profiles[0].MarshalJSON(dest)
for i := 1; i < len(orig.Profiles); i++ {
dest.WriteMore()
orig.Profiles[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.SchemaUrl != "" {
dest.WriteObjectField("schemaUrl")
dest.WriteString(orig.SchemaUrl)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ScopeProfiles) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "scope":
orig.Scope.UnmarshalJSON(iter)
case "profiles":
for iter.ReadArray() {
orig.Profiles = append(orig.Profiles, NewProfile())
orig.Profiles[len(orig.Profiles)-1].UnmarshalJSON(iter)
}
case "schemaUrl", "schema_url":
orig.SchemaUrl = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ScopeProfiles) SizeProto() int {
var n int
var l int
_ = l
l = orig.Scope.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
for i := range orig.Profiles {
l = orig.Profiles[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.SchemaUrl)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ScopeProfiles) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.Scope.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
for i := len(orig.Profiles) - 1; i >= 0; i-- {
l = orig.Profiles[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = len(orig.SchemaUrl)
if l > 0 {
pos -= l
copy(buf[pos:], orig.SchemaUrl)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
return len(buf) - pos
}
func (orig *ScopeProfiles) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Scope", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Scope.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Profiles", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Profiles = append(orig.Profiles, NewProfile())
err = orig.Profiles[len(orig.Profiles)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SchemaUrl", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SchemaUrl = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestScopeProfiles() *ScopeProfiles {
orig := NewScopeProfiles()
orig.Scope = *GenTestInstrumentationScope()
orig.Profiles = []*Profile{{}, GenTestProfile()}
orig.SchemaUrl = "test_schemaurl"
return orig
}
func GenTestScopeProfilesPtrSlice() []*ScopeProfiles {
orig := make([]*ScopeProfiles, 5)
orig[0] = NewScopeProfiles()
orig[1] = GenTestScopeProfiles()
orig[2] = NewScopeProfiles()
orig[3] = GenTestScopeProfiles()
orig[4] = NewScopeProfiles()
return orig
}
func GenTestScopeProfilesSlice() []ScopeProfiles {
orig := make([]ScopeProfiles, 5)
orig[1] = *GenTestScopeProfiles()
orig[3] = *GenTestScopeProfiles()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ScopeSpans is a collection of spans from a LibraryInstrumentation.
type ScopeSpans struct {
SchemaUrl string
Spans []*Span
Scope InstrumentationScope
}
var (
protoPoolScopeSpans = sync.Pool{
New: func() any {
return &ScopeSpans{}
},
}
)
func NewScopeSpans() *ScopeSpans {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ScopeSpans{}
}
return protoPoolScopeSpans.Get().(*ScopeSpans)
}
func DeleteScopeSpans(orig *ScopeSpans, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteInstrumentationScope(&orig.Scope, false)
for i := range orig.Spans {
DeleteSpan(orig.Spans[i], true)
}
orig.Reset()
if nullable {
protoPoolScopeSpans.Put(orig)
}
}
func CopyScopeSpans(dest, src *ScopeSpans) *ScopeSpans {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewScopeSpans()
}
CopyInstrumentationScope(&dest.Scope, &src.Scope)
dest.Spans = CopySpanPtrSlice(dest.Spans, src.Spans)
dest.SchemaUrl = src.SchemaUrl
return dest
}
func CopyScopeSpansSlice(dest, src []ScopeSpans) []ScopeSpans {
var newDest []ScopeSpans
if cap(dest) < len(src) {
newDest = make([]ScopeSpans, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteScopeSpans(&dest[i], false)
}
}
for i := range src {
CopyScopeSpans(&newDest[i], &src[i])
}
return newDest
}
func CopyScopeSpansPtrSlice(dest, src []*ScopeSpans) []*ScopeSpans {
var newDest []*ScopeSpans
if cap(dest) < len(src) {
newDest = make([]*ScopeSpans, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewScopeSpans()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteScopeSpans(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewScopeSpans()
}
}
for i := range src {
CopyScopeSpans(newDest[i], src[i])
}
return newDest
}
func (orig *ScopeSpans) Reset() {
*orig = ScopeSpans{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ScopeSpans) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
dest.WriteObjectField("scope")
orig.Scope.MarshalJSON(dest)
if len(orig.Spans) > 0 {
dest.WriteObjectField("spans")
dest.WriteArrayStart()
orig.Spans[0].MarshalJSON(dest)
for i := 1; i < len(orig.Spans); i++ {
dest.WriteMore()
orig.Spans[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.SchemaUrl != "" {
dest.WriteObjectField("schemaUrl")
dest.WriteString(orig.SchemaUrl)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ScopeSpans) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "scope":
orig.Scope.UnmarshalJSON(iter)
case "spans":
for iter.ReadArray() {
orig.Spans = append(orig.Spans, NewSpan())
orig.Spans[len(orig.Spans)-1].UnmarshalJSON(iter)
}
case "schemaUrl", "schema_url":
orig.SchemaUrl = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ScopeSpans) SizeProto() int {
var n int
var l int
_ = l
l = orig.Scope.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
for i := range orig.Spans {
l = orig.Spans[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.SchemaUrl)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *ScopeSpans) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.Scope.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
for i := len(orig.Spans) - 1; i >= 0; i-- {
l = orig.Spans[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = len(orig.SchemaUrl)
if l > 0 {
pos -= l
copy(buf[pos:], orig.SchemaUrl)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
return len(buf) - pos
}
func (orig *ScopeSpans) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Scope", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Scope.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Spans", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Spans = append(orig.Spans, NewSpan())
err = orig.Spans[len(orig.Spans)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SchemaUrl", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.SchemaUrl = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestScopeSpans() *ScopeSpans {
orig := NewScopeSpans()
orig.Scope = *GenTestInstrumentationScope()
orig.Spans = []*Span{{}, GenTestSpan()}
orig.SchemaUrl = "test_schemaurl"
return orig
}
func GenTestScopeSpansPtrSlice() []*ScopeSpans {
orig := make([]*ScopeSpans, 5)
orig[0] = NewScopeSpans()
orig[1] = GenTestScopeSpans()
orig[2] = NewScopeSpans()
orig[3] = GenTestScopeSpans()
orig[4] = NewScopeSpans()
return orig
}
func GenTestScopeSpansSlice() []ScopeSpans {
orig := make([]ScopeSpans, 5)
orig[1] = *GenTestScopeSpans()
orig[3] = *GenTestScopeSpans()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Span represents a single operation within a trace.
// See Span definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto
type Span struct {
TraceState string
Name string
Attributes []KeyValue
Events []*SpanEvent
Links []*SpanLink
Status Status
StartTimeUnixNano uint64
EndTimeUnixNano uint64
Flags uint32
Kind SpanKind
DroppedAttributesCount uint32
DroppedEventsCount uint32
DroppedLinksCount uint32
TraceId TraceID
SpanId SpanID
ParentSpanId SpanID
}
var (
protoPoolSpan = sync.Pool{
New: func() any {
return &Span{}
},
}
)
func NewSpan() *Span {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Span{}
}
return protoPoolSpan.Get().(*Span)
}
func DeleteSpan(orig *Span, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteTraceID(&orig.TraceId, false)
DeleteSpanID(&orig.SpanId, false)
DeleteSpanID(&orig.ParentSpanId, false)
for i := range orig.Attributes {
DeleteKeyValue(&orig.Attributes[i], false)
}
for i := range orig.Events {
DeleteSpanEvent(orig.Events[i], true)
}
for i := range orig.Links {
DeleteSpanLink(orig.Links[i], true)
}
DeleteStatus(&orig.Status, false)
orig.Reset()
if nullable {
protoPoolSpan.Put(orig)
}
}
func CopySpan(dest, src *Span) *Span {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewSpan()
}
CopyTraceID(&dest.TraceId, &src.TraceId)
CopySpanID(&dest.SpanId, &src.SpanId)
dest.TraceState = src.TraceState
CopySpanID(&dest.ParentSpanId, &src.ParentSpanId)
dest.Flags = src.Flags
dest.Name = src.Name
dest.Kind = src.Kind
dest.StartTimeUnixNano = src.StartTimeUnixNano
dest.EndTimeUnixNano = src.EndTimeUnixNano
dest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)
dest.DroppedAttributesCount = src.DroppedAttributesCount
dest.Events = CopySpanEventPtrSlice(dest.Events, src.Events)
dest.DroppedEventsCount = src.DroppedEventsCount
dest.Links = CopySpanLinkPtrSlice(dest.Links, src.Links)
dest.DroppedLinksCount = src.DroppedLinksCount
CopyStatus(&dest.Status, &src.Status)
return dest
}
func CopySpanSlice(dest, src []Span) []Span {
var newDest []Span
if cap(dest) < len(src) {
newDest = make([]Span, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSpan(&dest[i], false)
}
}
for i := range src {
CopySpan(&newDest[i], &src[i])
}
return newDest
}
func CopySpanPtrSlice(dest, src []*Span) []*Span {
var newDest []*Span
if cap(dest) < len(src) {
newDest = make([]*Span, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSpan()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSpan(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSpan()
}
}
for i := range src {
CopySpan(newDest[i], src[i])
}
return newDest
}
func (orig *Span) Reset() {
*orig = Span{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Span) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if !orig.TraceId.IsEmpty() {
dest.WriteObjectField("traceId")
orig.TraceId.MarshalJSON(dest)
}
if !orig.SpanId.IsEmpty() {
dest.WriteObjectField("spanId")
orig.SpanId.MarshalJSON(dest)
}
if orig.TraceState != "" {
dest.WriteObjectField("traceState")
dest.WriteString(orig.TraceState)
}
if !orig.ParentSpanId.IsEmpty() {
dest.WriteObjectField("parentSpanId")
orig.ParentSpanId.MarshalJSON(dest)
}
if orig.Flags != uint32(0) {
dest.WriteObjectField("flags")
dest.WriteUint32(orig.Flags)
}
if orig.Name != "" {
dest.WriteObjectField("name")
dest.WriteString(orig.Name)
}
if int32(orig.Kind) != 0 {
dest.WriteObjectField("kind")
dest.WriteInt32(int32(orig.Kind))
}
if orig.StartTimeUnixNano != uint64(0) {
dest.WriteObjectField("startTimeUnixNano")
dest.WriteUint64(orig.StartTimeUnixNano)
}
if orig.EndTimeUnixNano != uint64(0) {
dest.WriteObjectField("endTimeUnixNano")
dest.WriteUint64(orig.EndTimeUnixNano)
}
if len(orig.Attributes) > 0 {
dest.WriteObjectField("attributes")
dest.WriteArrayStart()
orig.Attributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.Attributes); i++ {
dest.WriteMore()
orig.Attributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.DroppedAttributesCount != uint32(0) {
dest.WriteObjectField("droppedAttributesCount")
dest.WriteUint32(orig.DroppedAttributesCount)
}
if len(orig.Events) > 0 {
dest.WriteObjectField("events")
dest.WriteArrayStart()
orig.Events[0].MarshalJSON(dest)
for i := 1; i < len(orig.Events); i++ {
dest.WriteMore()
orig.Events[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.DroppedEventsCount != uint32(0) {
dest.WriteObjectField("droppedEventsCount")
dest.WriteUint32(orig.DroppedEventsCount)
}
if len(orig.Links) > 0 {
dest.WriteObjectField("links")
dest.WriteArrayStart()
orig.Links[0].MarshalJSON(dest)
for i := 1; i < len(orig.Links); i++ {
dest.WriteMore()
orig.Links[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.DroppedLinksCount != uint32(0) {
dest.WriteObjectField("droppedLinksCount")
dest.WriteUint32(orig.DroppedLinksCount)
}
dest.WriteObjectField("status")
orig.Status.MarshalJSON(dest)
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Span) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "traceId", "trace_id":
orig.TraceId.UnmarshalJSON(iter)
case "spanId", "span_id":
orig.SpanId.UnmarshalJSON(iter)
case "traceState", "trace_state":
orig.TraceState = iter.ReadString()
case "parentSpanId", "parent_span_id":
orig.ParentSpanId.UnmarshalJSON(iter)
case "flags":
orig.Flags = iter.ReadUint32()
case "name":
orig.Name = iter.ReadString()
case "kind":
orig.Kind = SpanKind(iter.ReadEnumValue(SpanKind_value))
case "startTimeUnixNano", "start_time_unix_nano":
orig.StartTimeUnixNano = iter.ReadUint64()
case "endTimeUnixNano", "end_time_unix_nano":
orig.EndTimeUnixNano = iter.ReadUint64()
case "attributes":
for iter.ReadArray() {
orig.Attributes = append(orig.Attributes, KeyValue{})
orig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)
}
case "droppedAttributesCount", "dropped_attributes_count":
orig.DroppedAttributesCount = iter.ReadUint32()
case "events":
for iter.ReadArray() {
orig.Events = append(orig.Events, NewSpanEvent())
orig.Events[len(orig.Events)-1].UnmarshalJSON(iter)
}
case "droppedEventsCount", "dropped_events_count":
orig.DroppedEventsCount = iter.ReadUint32()
case "links":
for iter.ReadArray() {
orig.Links = append(orig.Links, NewSpanLink())
orig.Links[len(orig.Links)-1].UnmarshalJSON(iter)
}
case "droppedLinksCount", "dropped_links_count":
orig.DroppedLinksCount = iter.ReadUint32()
case "status":
orig.Status.UnmarshalJSON(iter)
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Span) SizeProto() int {
var n int
var l int
_ = l
l = orig.TraceId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
l = orig.SpanId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
l = len(orig.TraceState)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
l = orig.ParentSpanId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.Flags != uint32(0) {
n += 6
}
l = len(orig.Name)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.Kind != SpanKind(0) {
n += 1 + proto.Sov(uint64(orig.Kind))
}
if orig.StartTimeUnixNano != uint64(0) {
n += 9
}
if orig.EndTimeUnixNano != uint64(0) {
n += 9
}
for i := range orig.Attributes {
l = orig.Attributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.DroppedAttributesCount != uint32(0) {
n += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))
}
for i := range orig.Events {
l = orig.Events[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.DroppedEventsCount != uint32(0) {
n += 1 + proto.Sov(uint64(orig.DroppedEventsCount))
}
for i := range orig.Links {
l = orig.Links[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.DroppedLinksCount != uint32(0) {
n += 1 + proto.Sov(uint64(orig.DroppedLinksCount))
}
l = orig.Status.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
return n
}
func (orig *Span) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.TraceId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
l = orig.SpanId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
l = len(orig.TraceState)
if l > 0 {
pos -= l
copy(buf[pos:], orig.TraceState)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
l = orig.ParentSpanId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x22
if orig.Flags != uint32(0) {
pos -= 4
binary.LittleEndian.PutUint32(buf[pos:], uint32(orig.Flags))
pos--
buf[pos] = 0x1
pos--
buf[pos] = 0x85
}
l = len(orig.Name)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Name)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x2a
}
if orig.Kind != SpanKind(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Kind))
pos--
buf[pos] = 0x30
}
if orig.StartTimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.StartTimeUnixNano))
pos--
buf[pos] = 0x39
}
if orig.EndTimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.EndTimeUnixNano))
pos--
buf[pos] = 0x41
}
for i := len(orig.Attributes) - 1; i >= 0; i-- {
l = orig.Attributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x4a
}
if orig.DroppedAttributesCount != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))
pos--
buf[pos] = 0x50
}
for i := len(orig.Events) - 1; i >= 0; i-- {
l = orig.Events[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x5a
}
if orig.DroppedEventsCount != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedEventsCount))
pos--
buf[pos] = 0x60
}
for i := len(orig.Links) - 1; i >= 0; i-- {
l = orig.Links[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x6a
}
if orig.DroppedLinksCount != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedLinksCount))
pos--
buf[pos] = 0x70
}
l = orig.Status.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x7a
return len(buf) - pos
}
func (orig *Span) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TraceId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.TraceId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SpanId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.SpanId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TraceState", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.TraceState = string(buf[startPos:pos])
case 4:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ParentSpanId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.ParentSpanId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 16:
if wireType != proto.WireTypeI32 {
return fmt.Errorf("proto: wrong wireType = %d for field Flags", wireType)
}
var num uint32
num, pos, err = proto.ConsumeI32(buf, pos)
if err != nil {
return err
}
orig.Flags = uint32(num)
case 5:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Name = string(buf[startPos:pos])
case 6:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Kind = SpanKind(num)
case 7:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field StartTimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.StartTimeUnixNano = uint64(num)
case 8:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field EndTimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.EndTimeUnixNano = uint64(num)
case 9:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Attributes = append(orig.Attributes, KeyValue{})
err = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 10:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field DroppedAttributesCount", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.DroppedAttributesCount = uint32(num)
case 11:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Events = append(orig.Events, NewSpanEvent())
err = orig.Events[len(orig.Events)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 12:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field DroppedEventsCount", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.DroppedEventsCount = uint32(num)
case 13:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Links", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Links = append(orig.Links, NewSpanLink())
err = orig.Links[len(orig.Links)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 14:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field DroppedLinksCount", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.DroppedLinksCount = uint32(num)
case 15:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.Status.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestSpan() *Span {
orig := NewSpan()
orig.TraceId = *GenTestTraceID()
orig.SpanId = *GenTestSpanID()
orig.TraceState = "test_tracestate"
orig.ParentSpanId = *GenTestSpanID()
orig.Flags = uint32(13)
orig.Name = "test_name"
orig.Kind = SpanKind(13)
orig.StartTimeUnixNano = uint64(13)
orig.EndTimeUnixNano = uint64(13)
orig.Attributes = []KeyValue{{}, *GenTestKeyValue()}
orig.DroppedAttributesCount = uint32(13)
orig.Events = []*SpanEvent{{}, GenTestSpanEvent()}
orig.DroppedEventsCount = uint32(13)
orig.Links = []*SpanLink{{}, GenTestSpanLink()}
orig.DroppedLinksCount = uint32(13)
orig.Status = *GenTestStatus()
return orig
}
func GenTestSpanPtrSlice() []*Span {
orig := make([]*Span, 5)
orig[0] = NewSpan()
orig[1] = GenTestSpan()
orig[2] = NewSpan()
orig[3] = GenTestSpan()
orig[4] = NewSpan()
return orig
}
func GenTestSpanSlice() []Span {
orig := make([]Span, 5)
orig[1] = *GenTestSpan()
orig[3] = *GenTestSpan()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type SpanContext struct {
TraceState string
TraceFlags uint32
TraceID TraceID
SpanID SpanID
Remote bool
}
var (
protoPoolSpanContext = sync.Pool{
New: func() any {
return &SpanContext{}
},
}
)
func NewSpanContext() *SpanContext {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &SpanContext{}
}
return protoPoolSpanContext.Get().(*SpanContext)
}
func DeleteSpanContext(orig *SpanContext, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteTraceID(&orig.TraceID, false)
DeleteSpanID(&orig.SpanID, false)
orig.Reset()
if nullable {
protoPoolSpanContext.Put(orig)
}
}
func CopySpanContext(dest, src *SpanContext) *SpanContext {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewSpanContext()
}
CopyTraceID(&dest.TraceID, &src.TraceID)
CopySpanID(&dest.SpanID, &src.SpanID)
dest.TraceFlags = src.TraceFlags
dest.TraceState = src.TraceState
dest.Remote = src.Remote
return dest
}
func CopySpanContextSlice(dest, src []SpanContext) []SpanContext {
var newDest []SpanContext
if cap(dest) < len(src) {
newDest = make([]SpanContext, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSpanContext(&dest[i], false)
}
}
for i := range src {
CopySpanContext(&newDest[i], &src[i])
}
return newDest
}
func CopySpanContextPtrSlice(dest, src []*SpanContext) []*SpanContext {
var newDest []*SpanContext
if cap(dest) < len(src) {
newDest = make([]*SpanContext, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSpanContext()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSpanContext(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSpanContext()
}
}
for i := range src {
CopySpanContext(newDest[i], src[i])
}
return newDest
}
func (orig *SpanContext) Reset() {
*orig = SpanContext{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *SpanContext) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if !orig.TraceID.IsEmpty() {
dest.WriteObjectField("traceID")
orig.TraceID.MarshalJSON(dest)
}
if !orig.SpanID.IsEmpty() {
dest.WriteObjectField("spanID")
orig.SpanID.MarshalJSON(dest)
}
if orig.TraceFlags != uint32(0) {
dest.WriteObjectField("traceFlags")
dest.WriteUint32(orig.TraceFlags)
}
if orig.TraceState != "" {
dest.WriteObjectField("traceState")
dest.WriteString(orig.TraceState)
}
if orig.Remote != false {
dest.WriteObjectField("remote")
dest.WriteBool(orig.Remote)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *SpanContext) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "traceID", "trace_id":
orig.TraceID.UnmarshalJSON(iter)
case "spanID", "span_id":
orig.SpanID.UnmarshalJSON(iter)
case "traceFlags", "trace_flags":
orig.TraceFlags = iter.ReadUint32()
case "traceState", "trace_state":
orig.TraceState = iter.ReadString()
case "remote":
orig.Remote = iter.ReadBool()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *SpanContext) SizeProto() int {
var n int
var l int
_ = l
l = orig.TraceID.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
l = orig.SpanID.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.TraceFlags != uint32(0) {
n += 5
}
l = len(orig.TraceState)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.Remote != false {
n += 2
}
return n
}
func (orig *SpanContext) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.TraceID.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
l = orig.SpanID.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
if orig.TraceFlags != uint32(0) {
pos -= 4
binary.LittleEndian.PutUint32(buf[pos:], uint32(orig.TraceFlags))
pos--
buf[pos] = 0x1d
}
l = len(orig.TraceState)
if l > 0 {
pos -= l
copy(buf[pos:], orig.TraceState)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x22
}
if orig.Remote != false {
pos--
if orig.Remote {
buf[pos] = 1
} else {
buf[pos] = 0
}
pos--
buf[pos] = 0x28
}
return len(buf) - pos
}
func (orig *SpanContext) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TraceID", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.TraceID.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SpanID", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.SpanID.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeI32 {
return fmt.Errorf("proto: wrong wireType = %d for field TraceFlags", wireType)
}
var num uint32
num, pos, err = proto.ConsumeI32(buf, pos)
if err != nil {
return err
}
orig.TraceFlags = uint32(num)
case 4:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TraceState", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.TraceState = string(buf[startPos:pos])
case 5:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Remote", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Remote = num != 0
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestSpanContext() *SpanContext {
orig := NewSpanContext()
orig.TraceID = *GenTestTraceID()
orig.SpanID = *GenTestSpanID()
orig.TraceFlags = uint32(13)
orig.TraceState = "test_tracestate"
orig.Remote = true
return orig
}
func GenTestSpanContextPtrSlice() []*SpanContext {
orig := make([]*SpanContext, 5)
orig[0] = NewSpanContext()
orig[1] = GenTestSpanContext()
orig[2] = NewSpanContext()
orig[3] = GenTestSpanContext()
orig[4] = NewSpanContext()
return orig
}
func GenTestSpanContextSlice() []SpanContext {
orig := make([]SpanContext, 5)
orig[1] = *GenTestSpanContext()
orig[3] = *GenTestSpanContext()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// SpanEvent is a time-stamped annotation of the span, consisting of user-supplied
// text description and key-value pairs. See OTLP for event definition.
type SpanEvent struct {
Name string
Attributes []KeyValue
TimeUnixNano uint64
DroppedAttributesCount uint32
}
var (
protoPoolSpanEvent = sync.Pool{
New: func() any {
return &SpanEvent{}
},
}
)
func NewSpanEvent() *SpanEvent {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &SpanEvent{}
}
return protoPoolSpanEvent.Get().(*SpanEvent)
}
func DeleteSpanEvent(orig *SpanEvent, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.Attributes {
DeleteKeyValue(&orig.Attributes[i], false)
}
orig.Reset()
if nullable {
protoPoolSpanEvent.Put(orig)
}
}
func CopySpanEvent(dest, src *SpanEvent) *SpanEvent {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewSpanEvent()
}
dest.TimeUnixNano = src.TimeUnixNano
dest.Name = src.Name
dest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)
dest.DroppedAttributesCount = src.DroppedAttributesCount
return dest
}
func CopySpanEventSlice(dest, src []SpanEvent) []SpanEvent {
var newDest []SpanEvent
if cap(dest) < len(src) {
newDest = make([]SpanEvent, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSpanEvent(&dest[i], false)
}
}
for i := range src {
CopySpanEvent(&newDest[i], &src[i])
}
return newDest
}
func CopySpanEventPtrSlice(dest, src []*SpanEvent) []*SpanEvent {
var newDest []*SpanEvent
if cap(dest) < len(src) {
newDest = make([]*SpanEvent, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSpanEvent()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSpanEvent(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSpanEvent()
}
}
for i := range src {
CopySpanEvent(newDest[i], src[i])
}
return newDest
}
func (orig *SpanEvent) Reset() {
*orig = SpanEvent{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *SpanEvent) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.TimeUnixNano != uint64(0) {
dest.WriteObjectField("timeUnixNano")
dest.WriteUint64(orig.TimeUnixNano)
}
if orig.Name != "" {
dest.WriteObjectField("name")
dest.WriteString(orig.Name)
}
if len(orig.Attributes) > 0 {
dest.WriteObjectField("attributes")
dest.WriteArrayStart()
orig.Attributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.Attributes); i++ {
dest.WriteMore()
orig.Attributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.DroppedAttributesCount != uint32(0) {
dest.WriteObjectField("droppedAttributesCount")
dest.WriteUint32(orig.DroppedAttributesCount)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *SpanEvent) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "timeUnixNano", "time_unix_nano":
orig.TimeUnixNano = iter.ReadUint64()
case "name":
orig.Name = iter.ReadString()
case "attributes":
for iter.ReadArray() {
orig.Attributes = append(orig.Attributes, KeyValue{})
orig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)
}
case "droppedAttributesCount", "dropped_attributes_count":
orig.DroppedAttributesCount = iter.ReadUint32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *SpanEvent) SizeProto() int {
var n int
var l int
_ = l
if orig.TimeUnixNano != uint64(0) {
n += 9
}
l = len(orig.Name)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.Attributes {
l = orig.Attributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.DroppedAttributesCount != uint32(0) {
n += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))
}
return n
}
func (orig *SpanEvent) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.TimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))
pos--
buf[pos] = 0x9
}
l = len(orig.Name)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Name)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
for i := len(orig.Attributes) - 1; i >= 0; i-- {
l = orig.Attributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
if orig.DroppedAttributesCount != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))
pos--
buf[pos] = 0x20
}
return len(buf) - pos
}
func (orig *SpanEvent) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field TimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.TimeUnixNano = uint64(num)
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Name = string(buf[startPos:pos])
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Attributes = append(orig.Attributes, KeyValue{})
err = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 4:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field DroppedAttributesCount", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.DroppedAttributesCount = uint32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestSpanEvent() *SpanEvent {
orig := NewSpanEvent()
orig.TimeUnixNano = uint64(13)
orig.Name = "test_name"
orig.Attributes = []KeyValue{{}, *GenTestKeyValue()}
orig.DroppedAttributesCount = uint32(13)
return orig
}
func GenTestSpanEventPtrSlice() []*SpanEvent {
orig := make([]*SpanEvent, 5)
orig[0] = NewSpanEvent()
orig[1] = GenTestSpanEvent()
orig[2] = NewSpanEvent()
orig[3] = GenTestSpanEvent()
orig[4] = NewSpanEvent()
return orig
}
func GenTestSpanEventSlice() []SpanEvent {
orig := make([]SpanEvent, 5)
orig[1] = *GenTestSpanEvent()
orig[3] = *GenTestSpanEvent()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// SpanLink is a pointer from the current span to another span in the same trace or in a
// different trace.
// See Link definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto
type SpanLink struct {
TraceState string
Attributes []KeyValue
DroppedAttributesCount uint32
Flags uint32
TraceId TraceID
SpanId SpanID
}
var (
protoPoolSpanLink = sync.Pool{
New: func() any {
return &SpanLink{}
},
}
)
func NewSpanLink() *SpanLink {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &SpanLink{}
}
return protoPoolSpanLink.Get().(*SpanLink)
}
func DeleteSpanLink(orig *SpanLink, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteTraceID(&orig.TraceId, false)
DeleteSpanID(&orig.SpanId, false)
for i := range orig.Attributes {
DeleteKeyValue(&orig.Attributes[i], false)
}
orig.Reset()
if nullable {
protoPoolSpanLink.Put(orig)
}
}
func CopySpanLink(dest, src *SpanLink) *SpanLink {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewSpanLink()
}
CopyTraceID(&dest.TraceId, &src.TraceId)
CopySpanID(&dest.SpanId, &src.SpanId)
dest.TraceState = src.TraceState
dest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)
dest.DroppedAttributesCount = src.DroppedAttributesCount
dest.Flags = src.Flags
return dest
}
func CopySpanLinkSlice(dest, src []SpanLink) []SpanLink {
var newDest []SpanLink
if cap(dest) < len(src) {
newDest = make([]SpanLink, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSpanLink(&dest[i], false)
}
}
for i := range src {
CopySpanLink(&newDest[i], &src[i])
}
return newDest
}
func CopySpanLinkPtrSlice(dest, src []*SpanLink) []*SpanLink {
var newDest []*SpanLink
if cap(dest) < len(src) {
newDest = make([]*SpanLink, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSpanLink()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSpanLink(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSpanLink()
}
}
for i := range src {
CopySpanLink(newDest[i], src[i])
}
return newDest
}
func (orig *SpanLink) Reset() {
*orig = SpanLink{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *SpanLink) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if !orig.TraceId.IsEmpty() {
dest.WriteObjectField("traceId")
orig.TraceId.MarshalJSON(dest)
}
if !orig.SpanId.IsEmpty() {
dest.WriteObjectField("spanId")
orig.SpanId.MarshalJSON(dest)
}
if orig.TraceState != "" {
dest.WriteObjectField("traceState")
dest.WriteString(orig.TraceState)
}
if len(orig.Attributes) > 0 {
dest.WriteObjectField("attributes")
dest.WriteArrayStart()
orig.Attributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.Attributes); i++ {
dest.WriteMore()
orig.Attributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.DroppedAttributesCount != uint32(0) {
dest.WriteObjectField("droppedAttributesCount")
dest.WriteUint32(orig.DroppedAttributesCount)
}
if orig.Flags != uint32(0) {
dest.WriteObjectField("flags")
dest.WriteUint32(orig.Flags)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *SpanLink) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "traceId", "trace_id":
orig.TraceId.UnmarshalJSON(iter)
case "spanId", "span_id":
orig.SpanId.UnmarshalJSON(iter)
case "traceState", "trace_state":
orig.TraceState = iter.ReadString()
case "attributes":
for iter.ReadArray() {
orig.Attributes = append(orig.Attributes, KeyValue{})
orig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)
}
case "droppedAttributesCount", "dropped_attributes_count":
orig.DroppedAttributesCount = iter.ReadUint32()
case "flags":
orig.Flags = iter.ReadUint32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *SpanLink) SizeProto() int {
var n int
var l int
_ = l
l = orig.TraceId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
l = orig.SpanId.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
l = len(orig.TraceState)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
for i := range orig.Attributes {
l = orig.Attributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.DroppedAttributesCount != uint32(0) {
n += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))
}
if orig.Flags != uint32(0) {
n += 5
}
return n
}
func (orig *SpanLink) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = orig.TraceId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
l = orig.SpanId.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
l = len(orig.TraceState)
if l > 0 {
pos -= l
copy(buf[pos:], orig.TraceState)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
for i := len(orig.Attributes) - 1; i >= 0; i-- {
l = orig.Attributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x22
}
if orig.DroppedAttributesCount != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))
pos--
buf[pos] = 0x28
}
if orig.Flags != uint32(0) {
pos -= 4
binary.LittleEndian.PutUint32(buf[pos:], uint32(orig.Flags))
pos--
buf[pos] = 0x35
}
return len(buf) - pos
}
func (orig *SpanLink) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TraceId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.TraceId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field SpanId", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.SpanId.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TraceState", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.TraceState = string(buf[startPos:pos])
case 4:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Attributes = append(orig.Attributes, KeyValue{})
err = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 5:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field DroppedAttributesCount", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.DroppedAttributesCount = uint32(num)
case 6:
if wireType != proto.WireTypeI32 {
return fmt.Errorf("proto: wrong wireType = %d for field Flags", wireType)
}
var num uint32
num, pos, err = proto.ConsumeI32(buf, pos)
if err != nil {
return err
}
orig.Flags = uint32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestSpanLink() *SpanLink {
orig := NewSpanLink()
orig.TraceId = *GenTestTraceID()
orig.SpanId = *GenTestSpanID()
orig.TraceState = "test_tracestate"
orig.Attributes = []KeyValue{{}, *GenTestKeyValue()}
orig.DroppedAttributesCount = uint32(13)
orig.Flags = uint32(13)
return orig
}
func GenTestSpanLinkPtrSlice() []*SpanLink {
orig := make([]*SpanLink, 5)
orig[0] = NewSpanLink()
orig[1] = GenTestSpanLink()
orig[2] = NewSpanLink()
orig[3] = GenTestSpanLink()
orig[4] = NewSpanLink()
return orig
}
func GenTestSpanLinkSlice() []SpanLink {
orig := make([]SpanLink, 5)
orig[1] = *GenTestSpanLink()
orig[3] = *GenTestSpanLink()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Stack represents a stack trace as a list of locations.
type Stack struct {
LocationIndices []int32
}
var (
protoPoolStack = sync.Pool{
New: func() any {
return &Stack{}
},
}
)
func NewStack() *Stack {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Stack{}
}
return protoPoolStack.Get().(*Stack)
}
func DeleteStack(orig *Stack, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolStack.Put(orig)
}
}
func CopyStack(dest, src *Stack) *Stack {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewStack()
}
dest.LocationIndices = append(dest.LocationIndices[:0], src.LocationIndices...)
return dest
}
func CopyStackSlice(dest, src []Stack) []Stack {
var newDest []Stack
if cap(dest) < len(src) {
newDest = make([]Stack, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteStack(&dest[i], false)
}
}
for i := range src {
CopyStack(&newDest[i], &src[i])
}
return newDest
}
func CopyStackPtrSlice(dest, src []*Stack) []*Stack {
var newDest []*Stack
if cap(dest) < len(src) {
newDest = make([]*Stack, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewStack()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteStack(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewStack()
}
}
for i := range src {
CopyStack(newDest[i], src[i])
}
return newDest
}
func (orig *Stack) Reset() {
*orig = Stack{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Stack) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.LocationIndices) > 0 {
dest.WriteObjectField("locationIndices")
dest.WriteArrayStart()
dest.WriteInt32(orig.LocationIndices[0])
for i := 1; i < len(orig.LocationIndices); i++ {
dest.WriteMore()
dest.WriteInt32(orig.LocationIndices[i])
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Stack) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "locationIndices", "location_indices":
for iter.ReadArray() {
orig.LocationIndices = append(orig.LocationIndices, iter.ReadInt32())
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Stack) SizeProto() int {
var n int
var l int
_ = l
if len(orig.LocationIndices) > 0 {
l = 0
for _, e := range orig.LocationIndices {
l += proto.Sov(uint64(e))
}
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *Stack) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = len(orig.LocationIndices)
if l > 0 {
endPos := pos
for i := l - 1; i >= 0; i-- {
pos = proto.EncodeVarint(buf, pos, uint64(orig.LocationIndices[i]))
}
pos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *Stack) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
switch wireType {
case proto.WireTypeLen:
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
var num uint64
for startPos < pos {
num, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)
if err != nil {
return err
}
orig.LocationIndices = append(orig.LocationIndices, int32(num))
}
if startPos != pos {
return fmt.Errorf("proto: invalid field len = %d for field LocationIndices", pos-startPos)
}
case proto.WireTypeVarint:
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.LocationIndices = append(orig.LocationIndices, int32(num))
default:
return fmt.Errorf("proto: wrong wireType = %d for field LocationIndices", wireType)
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestStack() *Stack {
orig := NewStack()
orig.LocationIndices = []int32{int32(0), int32(13)}
return orig
}
func GenTestStackPtrSlice() []*Stack {
orig := make([]*Stack, 5)
orig[0] = NewStack()
orig[1] = GenTestStack()
orig[2] = NewStack()
orig[3] = GenTestStack()
orig[4] = NewStack()
return orig
}
func GenTestStackSlice() []Stack {
orig := make([]Stack, 5)
orig[1] = *GenTestStack()
orig[3] = *GenTestStack()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Status is an optional final status for this span. Semantically, when Status was not
// set, that means the span ended without errors and to assume Status.Ok (code = 0).
type Status struct {
Message string
Code StatusCode
}
var (
protoPoolStatus = sync.Pool{
New: func() any {
return &Status{}
},
}
)
func NewStatus() *Status {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Status{}
}
return protoPoolStatus.Get().(*Status)
}
func DeleteStatus(orig *Status, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolStatus.Put(orig)
}
}
func CopyStatus(dest, src *Status) *Status {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewStatus()
}
dest.Message = src.Message
dest.Code = src.Code
return dest
}
func CopyStatusSlice(dest, src []Status) []Status {
var newDest []Status
if cap(dest) < len(src) {
newDest = make([]Status, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteStatus(&dest[i], false)
}
}
for i := range src {
CopyStatus(&newDest[i], &src[i])
}
return newDest
}
func CopyStatusPtrSlice(dest, src []*Status) []*Status {
var newDest []*Status
if cap(dest) < len(src) {
newDest = make([]*Status, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewStatus()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteStatus(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewStatus()
}
}
for i := range src {
CopyStatus(newDest[i], src[i])
}
return newDest
}
func (orig *Status) Reset() {
*orig = Status{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Status) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.Message != "" {
dest.WriteObjectField("message")
dest.WriteString(orig.Message)
}
if int32(orig.Code) != 0 {
dest.WriteObjectField("code")
dest.WriteInt32(int32(orig.Code))
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Status) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "message":
orig.Message = iter.ReadString()
case "code":
orig.Code = StatusCode(iter.ReadEnumValue(StatusCode_value))
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Status) SizeProto() int {
var n int
var l int
_ = l
l = len(orig.Message)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.Code != StatusCode(0) {
n += 1 + proto.Sov(uint64(orig.Code))
}
return n
}
func (orig *Status) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = len(orig.Message)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Message)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
if orig.Code != StatusCode(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Code))
pos--
buf[pos] = 0x18
}
return len(buf) - pos
}
func (orig *Status) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Message = string(buf[startPos:pos])
case 3:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Code = StatusCode(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestStatus() *Status {
orig := NewStatus()
orig.Message = "test_message"
orig.Code = StatusCode(13)
return orig
}
func GenTestStatusPtrSlice() []*Status {
orig := make([]*Status, 5)
orig[0] = NewStatus()
orig[1] = GenTestStatus()
orig[2] = NewStatus()
orig[3] = GenTestStatus()
orig[4] = NewStatus()
return orig
}
func GenTestStatusSlice() []Status {
orig := make([]Status, 5)
orig[1] = *GenTestStatus()
orig[3] = *GenTestStatus()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Sum represents the type of a numeric metric that is calculated as a sum of all reported measurements over a time interval.
type Sum struct {
DataPoints []*NumberDataPoint
AggregationTemporality AggregationTemporality
IsMonotonic bool
}
var (
protoPoolSum = sync.Pool{
New: func() any {
return &Sum{}
},
}
)
func NewSum() *Sum {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Sum{}
}
return protoPoolSum.Get().(*Sum)
}
func DeleteSum(orig *Sum, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.DataPoints {
DeleteNumberDataPoint(orig.DataPoints[i], true)
}
orig.Reset()
if nullable {
protoPoolSum.Put(orig)
}
}
func CopySum(dest, src *Sum) *Sum {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewSum()
}
dest.DataPoints = CopyNumberDataPointPtrSlice(dest.DataPoints, src.DataPoints)
dest.AggregationTemporality = src.AggregationTemporality
dest.IsMonotonic = src.IsMonotonic
return dest
}
func CopySumSlice(dest, src []Sum) []Sum {
var newDest []Sum
if cap(dest) < len(src) {
newDest = make([]Sum, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSum(&dest[i], false)
}
}
for i := range src {
CopySum(&newDest[i], &src[i])
}
return newDest
}
func CopySumPtrSlice(dest, src []*Sum) []*Sum {
var newDest []*Sum
if cap(dest) < len(src) {
newDest = make([]*Sum, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSum()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSum(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSum()
}
}
for i := range src {
CopySum(newDest[i], src[i])
}
return newDest
}
func (orig *Sum) Reset() {
*orig = Sum{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Sum) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.DataPoints) > 0 {
dest.WriteObjectField("dataPoints")
dest.WriteArrayStart()
orig.DataPoints[0].MarshalJSON(dest)
for i := 1; i < len(orig.DataPoints); i++ {
dest.WriteMore()
orig.DataPoints[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if int32(orig.AggregationTemporality) != 0 {
dest.WriteObjectField("aggregationTemporality")
dest.WriteInt32(int32(orig.AggregationTemporality))
}
if orig.IsMonotonic != false {
dest.WriteObjectField("isMonotonic")
dest.WriteBool(orig.IsMonotonic)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Sum) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "dataPoints", "data_points":
for iter.ReadArray() {
orig.DataPoints = append(orig.DataPoints, NewNumberDataPoint())
orig.DataPoints[len(orig.DataPoints)-1].UnmarshalJSON(iter)
}
case "aggregationTemporality", "aggregation_temporality":
orig.AggregationTemporality = AggregationTemporality(iter.ReadEnumValue(AggregationTemporality_value))
case "isMonotonic", "is_monotonic":
orig.IsMonotonic = iter.ReadBool()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Sum) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.DataPoints {
l = orig.DataPoints[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.AggregationTemporality != AggregationTemporality(0) {
n += 1 + proto.Sov(uint64(orig.AggregationTemporality))
}
if orig.IsMonotonic != false {
n += 2
}
return n
}
func (orig *Sum) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.DataPoints) - 1; i >= 0; i-- {
l = orig.DataPoints[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
if orig.AggregationTemporality != AggregationTemporality(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.AggregationTemporality))
pos--
buf[pos] = 0x10
}
if orig.IsMonotonic != false {
pos--
if orig.IsMonotonic {
buf[pos] = 1
} else {
buf[pos] = 0
}
pos--
buf[pos] = 0x18
}
return len(buf) - pos
}
func (orig *Sum) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field DataPoints", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.DataPoints = append(orig.DataPoints, NewNumberDataPoint())
err = orig.DataPoints[len(orig.DataPoints)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field AggregationTemporality", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.AggregationTemporality = AggregationTemporality(num)
case 3:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field IsMonotonic", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.IsMonotonic = num != 0
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestSum() *Sum {
orig := NewSum()
orig.DataPoints = []*NumberDataPoint{{}, GenTestNumberDataPoint()}
orig.AggregationTemporality = AggregationTemporality(13)
orig.IsMonotonic = true
return orig
}
func GenTestSumPtrSlice() []*Sum {
orig := make([]*Sum, 5)
orig[0] = NewSum()
orig[1] = GenTestSum()
orig[2] = NewSum()
orig[3] = GenTestSum()
orig[4] = NewSum()
return orig
}
func GenTestSumSlice() []Sum {
orig := make([]Sum, 5)
orig[1] = *GenTestSum()
orig[3] = *GenTestSum()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// Summary represents the type of a metric that is calculated by aggregating as a Summary of all reported double measurements over a time interval.
type Summary struct {
DataPoints []*SummaryDataPoint
}
var (
protoPoolSummary = sync.Pool{
New: func() any {
return &Summary{}
},
}
)
func NewSummary() *Summary {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &Summary{}
}
return protoPoolSummary.Get().(*Summary)
}
func DeleteSummary(orig *Summary, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.DataPoints {
DeleteSummaryDataPoint(orig.DataPoints[i], true)
}
orig.Reset()
if nullable {
protoPoolSummary.Put(orig)
}
}
func CopySummary(dest, src *Summary) *Summary {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewSummary()
}
dest.DataPoints = CopySummaryDataPointPtrSlice(dest.DataPoints, src.DataPoints)
return dest
}
func CopySummarySlice(dest, src []Summary) []Summary {
var newDest []Summary
if cap(dest) < len(src) {
newDest = make([]Summary, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSummary(&dest[i], false)
}
}
for i := range src {
CopySummary(&newDest[i], &src[i])
}
return newDest
}
func CopySummaryPtrSlice(dest, src []*Summary) []*Summary {
var newDest []*Summary
if cap(dest) < len(src) {
newDest = make([]*Summary, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSummary()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSummary(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSummary()
}
}
for i := range src {
CopySummary(newDest[i], src[i])
}
return newDest
}
func (orig *Summary) Reset() {
*orig = Summary{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *Summary) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.DataPoints) > 0 {
dest.WriteObjectField("dataPoints")
dest.WriteArrayStart()
orig.DataPoints[0].MarshalJSON(dest)
for i := 1; i < len(orig.DataPoints); i++ {
dest.WriteMore()
orig.DataPoints[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *Summary) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "dataPoints", "data_points":
for iter.ReadArray() {
orig.DataPoints = append(orig.DataPoints, NewSummaryDataPoint())
orig.DataPoints[len(orig.DataPoints)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *Summary) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.DataPoints {
l = orig.DataPoints[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *Summary) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.DataPoints) - 1; i >= 0; i-- {
l = orig.DataPoints[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *Summary) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field DataPoints", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.DataPoints = append(orig.DataPoints, NewSummaryDataPoint())
err = orig.DataPoints[len(orig.DataPoints)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestSummary() *Summary {
orig := NewSummary()
orig.DataPoints = []*SummaryDataPoint{{}, GenTestSummaryDataPoint()}
return orig
}
func GenTestSummaryPtrSlice() []*Summary {
orig := make([]*Summary, 5)
orig[0] = NewSummary()
orig[1] = GenTestSummary()
orig[2] = NewSummary()
orig[3] = GenTestSummary()
orig[4] = NewSummary()
return orig
}
func GenTestSummarySlice() []Summary {
orig := make([]Summary, 5)
orig[1] = *GenTestSummary()
orig[3] = *GenTestSummary()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"math"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// SummaryDataPoint is a single data point in a timeseries that describes the time-varying values of a Summary of double values.
type SummaryDataPoint struct {
Attributes []KeyValue
QuantileValues []*SummaryDataPointValueAtQuantile
StartTimeUnixNano uint64
TimeUnixNano uint64
Count uint64
Sum float64
Flags uint32
}
var (
protoPoolSummaryDataPoint = sync.Pool{
New: func() any {
return &SummaryDataPoint{}
},
}
)
func NewSummaryDataPoint() *SummaryDataPoint {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &SummaryDataPoint{}
}
return protoPoolSummaryDataPoint.Get().(*SummaryDataPoint)
}
func DeleteSummaryDataPoint(orig *SummaryDataPoint, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.Attributes {
DeleteKeyValue(&orig.Attributes[i], false)
}
for i := range orig.QuantileValues {
DeleteSummaryDataPointValueAtQuantile(orig.QuantileValues[i], true)
}
orig.Reset()
if nullable {
protoPoolSummaryDataPoint.Put(orig)
}
}
func CopySummaryDataPoint(dest, src *SummaryDataPoint) *SummaryDataPoint {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewSummaryDataPoint()
}
dest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)
dest.StartTimeUnixNano = src.StartTimeUnixNano
dest.TimeUnixNano = src.TimeUnixNano
dest.Count = src.Count
dest.Sum = src.Sum
dest.QuantileValues = CopySummaryDataPointValueAtQuantilePtrSlice(dest.QuantileValues, src.QuantileValues)
dest.Flags = src.Flags
return dest
}
func CopySummaryDataPointSlice(dest, src []SummaryDataPoint) []SummaryDataPoint {
var newDest []SummaryDataPoint
if cap(dest) < len(src) {
newDest = make([]SummaryDataPoint, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSummaryDataPoint(&dest[i], false)
}
}
for i := range src {
CopySummaryDataPoint(&newDest[i], &src[i])
}
return newDest
}
func CopySummaryDataPointPtrSlice(dest, src []*SummaryDataPoint) []*SummaryDataPoint {
var newDest []*SummaryDataPoint
if cap(dest) < len(src) {
newDest = make([]*SummaryDataPoint, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSummaryDataPoint()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSummaryDataPoint(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSummaryDataPoint()
}
}
for i := range src {
CopySummaryDataPoint(newDest[i], src[i])
}
return newDest
}
func (orig *SummaryDataPoint) Reset() {
*orig = SummaryDataPoint{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *SummaryDataPoint) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.Attributes) > 0 {
dest.WriteObjectField("attributes")
dest.WriteArrayStart()
orig.Attributes[0].MarshalJSON(dest)
for i := 1; i < len(orig.Attributes); i++ {
dest.WriteMore()
orig.Attributes[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.StartTimeUnixNano != uint64(0) {
dest.WriteObjectField("startTimeUnixNano")
dest.WriteUint64(orig.StartTimeUnixNano)
}
if orig.TimeUnixNano != uint64(0) {
dest.WriteObjectField("timeUnixNano")
dest.WriteUint64(orig.TimeUnixNano)
}
if orig.Count != uint64(0) {
dest.WriteObjectField("count")
dest.WriteUint64(orig.Count)
}
if orig.Sum != float64(0) {
dest.WriteObjectField("sum")
dest.WriteFloat64(orig.Sum)
}
if len(orig.QuantileValues) > 0 {
dest.WriteObjectField("quantileValues")
dest.WriteArrayStart()
orig.QuantileValues[0].MarshalJSON(dest)
for i := 1; i < len(orig.QuantileValues); i++ {
dest.WriteMore()
orig.QuantileValues[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
if orig.Flags != uint32(0) {
dest.WriteObjectField("flags")
dest.WriteUint32(orig.Flags)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *SummaryDataPoint) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "attributes":
for iter.ReadArray() {
orig.Attributes = append(orig.Attributes, KeyValue{})
orig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)
}
case "startTimeUnixNano", "start_time_unix_nano":
orig.StartTimeUnixNano = iter.ReadUint64()
case "timeUnixNano", "time_unix_nano":
orig.TimeUnixNano = iter.ReadUint64()
case "count":
orig.Count = iter.ReadUint64()
case "sum":
orig.Sum = iter.ReadFloat64()
case "quantileValues", "quantile_values":
for iter.ReadArray() {
orig.QuantileValues = append(orig.QuantileValues, NewSummaryDataPointValueAtQuantile())
orig.QuantileValues[len(orig.QuantileValues)-1].UnmarshalJSON(iter)
}
case "flags":
orig.Flags = iter.ReadUint32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *SummaryDataPoint) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.Attributes {
l = orig.Attributes[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.StartTimeUnixNano != uint64(0) {
n += 9
}
if orig.TimeUnixNano != uint64(0) {
n += 9
}
if orig.Count != uint64(0) {
n += 9
}
if orig.Sum != float64(0) {
n += 9
}
for i := range orig.QuantileValues {
l = orig.QuantileValues[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.Flags != uint32(0) {
n += 1 + proto.Sov(uint64(orig.Flags))
}
return n
}
func (orig *SummaryDataPoint) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.Attributes) - 1; i >= 0; i-- {
l = orig.Attributes[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x3a
}
if orig.StartTimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.StartTimeUnixNano))
pos--
buf[pos] = 0x11
}
if orig.TimeUnixNano != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))
pos--
buf[pos] = 0x19
}
if orig.Count != uint64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], uint64(orig.Count))
pos--
buf[pos] = 0x21
}
if orig.Sum != float64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Sum))
pos--
buf[pos] = 0x29
}
for i := len(orig.QuantileValues) - 1; i >= 0; i-- {
l = orig.QuantileValues[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x32
}
if orig.Flags != uint32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Flags))
pos--
buf[pos] = 0x40
}
return len(buf) - pos
}
func (orig *SummaryDataPoint) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 7:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Attributes = append(orig.Attributes, KeyValue{})
err = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 2:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field StartTimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.StartTimeUnixNano = uint64(num)
case 3:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field TimeUnixNano", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.TimeUnixNano = uint64(num)
case 4:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Count", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.Count = uint64(num)
case 5:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Sum", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.Sum = math.Float64frombits(num)
case 6:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field QuantileValues", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.QuantileValues = append(orig.QuantileValues, NewSummaryDataPointValueAtQuantile())
err = orig.QuantileValues[len(orig.QuantileValues)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 8:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Flags", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Flags = uint32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestSummaryDataPoint() *SummaryDataPoint {
orig := NewSummaryDataPoint()
orig.Attributes = []KeyValue{{}, *GenTestKeyValue()}
orig.StartTimeUnixNano = uint64(13)
orig.TimeUnixNano = uint64(13)
orig.Count = uint64(13)
orig.Sum = float64(3.1415926)
orig.QuantileValues = []*SummaryDataPointValueAtQuantile{{}, GenTestSummaryDataPointValueAtQuantile()}
orig.Flags = uint32(13)
return orig
}
func GenTestSummaryDataPointPtrSlice() []*SummaryDataPoint {
orig := make([]*SummaryDataPoint, 5)
orig[0] = NewSummaryDataPoint()
orig[1] = GenTestSummaryDataPoint()
orig[2] = NewSummaryDataPoint()
orig[3] = GenTestSummaryDataPoint()
orig[4] = NewSummaryDataPoint()
return orig
}
func GenTestSummaryDataPointSlice() []SummaryDataPoint {
orig := make([]SummaryDataPoint, 5)
orig[1] = *GenTestSummaryDataPoint()
orig[3] = *GenTestSummaryDataPoint()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"math"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// SummaryDataPointValueAtQuantile is a quantile value within a Summary data point.
type SummaryDataPointValueAtQuantile struct {
Quantile float64
Value float64
}
var (
protoPoolSummaryDataPointValueAtQuantile = sync.Pool{
New: func() any {
return &SummaryDataPointValueAtQuantile{}
},
}
)
func NewSummaryDataPointValueAtQuantile() *SummaryDataPointValueAtQuantile {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &SummaryDataPointValueAtQuantile{}
}
return protoPoolSummaryDataPointValueAtQuantile.Get().(*SummaryDataPointValueAtQuantile)
}
func DeleteSummaryDataPointValueAtQuantile(orig *SummaryDataPointValueAtQuantile, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolSummaryDataPointValueAtQuantile.Put(orig)
}
}
func CopySummaryDataPointValueAtQuantile(dest, src *SummaryDataPointValueAtQuantile) *SummaryDataPointValueAtQuantile {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewSummaryDataPointValueAtQuantile()
}
dest.Quantile = src.Quantile
dest.Value = src.Value
return dest
}
func CopySummaryDataPointValueAtQuantileSlice(dest, src []SummaryDataPointValueAtQuantile) []SummaryDataPointValueAtQuantile {
var newDest []SummaryDataPointValueAtQuantile
if cap(dest) < len(src) {
newDest = make([]SummaryDataPointValueAtQuantile, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSummaryDataPointValueAtQuantile(&dest[i], false)
}
}
for i := range src {
CopySummaryDataPointValueAtQuantile(&newDest[i], &src[i])
}
return newDest
}
func CopySummaryDataPointValueAtQuantilePtrSlice(dest, src []*SummaryDataPointValueAtQuantile) []*SummaryDataPointValueAtQuantile {
var newDest []*SummaryDataPointValueAtQuantile
if cap(dest) < len(src) {
newDest = make([]*SummaryDataPointValueAtQuantile, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSummaryDataPointValueAtQuantile()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteSummaryDataPointValueAtQuantile(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewSummaryDataPointValueAtQuantile()
}
}
for i := range src {
CopySummaryDataPointValueAtQuantile(newDest[i], src[i])
}
return newDest
}
func (orig *SummaryDataPointValueAtQuantile) Reset() {
*orig = SummaryDataPointValueAtQuantile{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *SummaryDataPointValueAtQuantile) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.Quantile != float64(0) {
dest.WriteObjectField("quantile")
dest.WriteFloat64(orig.Quantile)
}
if orig.Value != float64(0) {
dest.WriteObjectField("value")
dest.WriteFloat64(orig.Value)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *SummaryDataPointValueAtQuantile) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "quantile":
orig.Quantile = iter.ReadFloat64()
case "value":
orig.Value = iter.ReadFloat64()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *SummaryDataPointValueAtQuantile) SizeProto() int {
var n int
var l int
_ = l
if orig.Quantile != float64(0) {
n += 9
}
if orig.Value != float64(0) {
n += 9
}
return n
}
func (orig *SummaryDataPointValueAtQuantile) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.Quantile != float64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Quantile))
pos--
buf[pos] = 0x9
}
if orig.Value != float64(0) {
pos -= 8
binary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Value))
pos--
buf[pos] = 0x11
}
return len(buf) - pos
}
func (orig *SummaryDataPointValueAtQuantile) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Quantile", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.Quantile = math.Float64frombits(num)
case 2:
if wireType != proto.WireTypeI64 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var num uint64
num, pos, err = proto.ConsumeI64(buf, pos)
if err != nil {
return err
}
orig.Value = math.Float64frombits(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestSummaryDataPointValueAtQuantile() *SummaryDataPointValueAtQuantile {
orig := NewSummaryDataPointValueAtQuantile()
orig.Quantile = float64(3.1415926)
orig.Value = float64(3.1415926)
return orig
}
func GenTestSummaryDataPointValueAtQuantilePtrSlice() []*SummaryDataPointValueAtQuantile {
orig := make([]*SummaryDataPointValueAtQuantile, 5)
orig[0] = NewSummaryDataPointValueAtQuantile()
orig[1] = GenTestSummaryDataPointValueAtQuantile()
orig[2] = NewSummaryDataPointValueAtQuantile()
orig[3] = GenTestSummaryDataPointValueAtQuantile()
orig[4] = NewSummaryDataPointValueAtQuantile()
return orig
}
func GenTestSummaryDataPointValueAtQuantileSlice() []SummaryDataPointValueAtQuantile {
orig := make([]SummaryDataPointValueAtQuantile, 5)
orig[1] = *GenTestSummaryDataPointValueAtQuantile()
orig[3] = *GenTestSummaryDataPointValueAtQuantile()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type TCPAddr struct {
Zone string
IP []byte
Port int64
}
var (
protoPoolTCPAddr = sync.Pool{
New: func() any {
return &TCPAddr{}
},
}
)
func NewTCPAddr() *TCPAddr {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &TCPAddr{}
}
return protoPoolTCPAddr.Get().(*TCPAddr)
}
func DeleteTCPAddr(orig *TCPAddr, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolTCPAddr.Put(orig)
}
}
func CopyTCPAddr(dest, src *TCPAddr) *TCPAddr {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewTCPAddr()
}
dest.IP = src.IP
dest.Port = src.Port
dest.Zone = src.Zone
return dest
}
func CopyTCPAddrSlice(dest, src []TCPAddr) []TCPAddr {
var newDest []TCPAddr
if cap(dest) < len(src) {
newDest = make([]TCPAddr, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteTCPAddr(&dest[i], false)
}
}
for i := range src {
CopyTCPAddr(&newDest[i], &src[i])
}
return newDest
}
func CopyTCPAddrPtrSlice(dest, src []*TCPAddr) []*TCPAddr {
var newDest []*TCPAddr
if cap(dest) < len(src) {
newDest = make([]*TCPAddr, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewTCPAddr()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteTCPAddr(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewTCPAddr()
}
}
for i := range src {
CopyTCPAddr(newDest[i], src[i])
}
return newDest
}
func (orig *TCPAddr) Reset() {
*orig = TCPAddr{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *TCPAddr) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.IP) > 0 {
dest.WriteObjectField("iP")
dest.WriteBytes(orig.IP)
}
if orig.Port != int64(0) {
dest.WriteObjectField("port")
dest.WriteInt64(orig.Port)
}
if orig.Zone != "" {
dest.WriteObjectField("zone")
dest.WriteString(orig.Zone)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *TCPAddr) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "iP":
orig.IP = iter.ReadBytes()
case "port":
orig.Port = iter.ReadInt64()
case "zone":
orig.Zone = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *TCPAddr) SizeProto() int {
var n int
var l int
_ = l
l = len(orig.IP)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.Port != int64(0) {
n += 1 + proto.Sov(uint64(orig.Port))
}
l = len(orig.Zone)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *TCPAddr) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = len(orig.IP)
if l > 0 {
pos -= l
copy(buf[pos:], orig.IP)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
if orig.Port != int64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Port))
pos--
buf[pos] = 0x10
}
l = len(orig.Zone)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Zone)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
return len(buf) - pos
}
func (orig *TCPAddr) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field IP", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
if length != 0 {
orig.IP = make([]byte, length)
copy(orig.IP, buf[startPos:pos])
}
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Port", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Port = int64(num)
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Zone", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Zone = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestTCPAddr() *TCPAddr {
orig := NewTCPAddr()
orig.IP = []byte{1, 2, 3}
orig.Port = int64(13)
orig.Zone = "test_zone"
return orig
}
func GenTestTCPAddrPtrSlice() []*TCPAddr {
orig := make([]*TCPAddr, 5)
orig[0] = NewTCPAddr()
orig[1] = GenTestTCPAddr()
orig[2] = NewTCPAddr()
orig[3] = GenTestTCPAddr()
orig[4] = NewTCPAddr()
return orig
}
func GenTestTCPAddrSlice() []TCPAddr {
orig := make([]TCPAddr, 5)
orig[1] = *GenTestTCPAddr()
orig[3] = *GenTestTCPAddr()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// TracesData represents the traces data that can be stored in a persistent storage,
// OR can be embedded by other protocols that transfer OTLP traces data but do not
// implement the OTLP protocol.
type TracesData struct {
ResourceSpans []*ResourceSpans
}
var (
protoPoolTracesData = sync.Pool{
New: func() any {
return &TracesData{}
},
}
)
func NewTracesData() *TracesData {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &TracesData{}
}
return protoPoolTracesData.Get().(*TracesData)
}
func DeleteTracesData(orig *TracesData, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
for i := range orig.ResourceSpans {
DeleteResourceSpans(orig.ResourceSpans[i], true)
}
orig.Reset()
if nullable {
protoPoolTracesData.Put(orig)
}
}
func CopyTracesData(dest, src *TracesData) *TracesData {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewTracesData()
}
dest.ResourceSpans = CopyResourceSpansPtrSlice(dest.ResourceSpans, src.ResourceSpans)
return dest
}
func CopyTracesDataSlice(dest, src []TracesData) []TracesData {
var newDest []TracesData
if cap(dest) < len(src) {
newDest = make([]TracesData, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteTracesData(&dest[i], false)
}
}
for i := range src {
CopyTracesData(&newDest[i], &src[i])
}
return newDest
}
func CopyTracesDataPtrSlice(dest, src []*TracesData) []*TracesData {
var newDest []*TracesData
if cap(dest) < len(src) {
newDest = make([]*TracesData, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewTracesData()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteTracesData(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewTracesData()
}
}
for i := range src {
CopyTracesData(newDest[i], src[i])
}
return newDest
}
func (orig *TracesData) Reset() {
*orig = TracesData{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *TracesData) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.ResourceSpans) > 0 {
dest.WriteObjectField("resourceSpans")
dest.WriteArrayStart()
orig.ResourceSpans[0].MarshalJSON(dest)
for i := 1; i < len(orig.ResourceSpans); i++ {
dest.WriteMore()
orig.ResourceSpans[i].MarshalJSON(dest)
}
dest.WriteArrayEnd()
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *TracesData) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "resourceSpans", "resource_spans":
for iter.ReadArray() {
orig.ResourceSpans = append(orig.ResourceSpans, NewResourceSpans())
orig.ResourceSpans[len(orig.ResourceSpans)-1].UnmarshalJSON(iter)
}
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *TracesData) SizeProto() int {
var n int
var l int
_ = l
for i := range orig.ResourceSpans {
l = orig.ResourceSpans[i].SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *TracesData) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
for i := len(orig.ResourceSpans) - 1; i >= 0; i-- {
l = orig.ResourceSpans[i].MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
return len(buf) - pos
}
func (orig *TracesData) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field ResourceSpans", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.ResourceSpans = append(orig.ResourceSpans, NewResourceSpans())
err = orig.ResourceSpans[len(orig.ResourceSpans)-1].UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestTracesData() *TracesData {
orig := NewTracesData()
orig.ResourceSpans = []*ResourceSpans{{}, GenTestResourceSpans()}
return orig
}
func GenTestTracesDataPtrSlice() []*TracesData {
orig := make([]*TracesData, 5)
orig[0] = NewTracesData()
orig[1] = GenTestTracesData()
orig[2] = NewTracesData()
orig[3] = GenTestTracesData()
orig[4] = NewTracesData()
return orig
}
func GenTestTracesDataSlice() []TracesData {
orig := make([]TracesData, 5)
orig[1] = *GenTestTracesData()
orig[3] = *GenTestTracesData()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"encoding/binary"
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type TracesRequest struct {
RequestContext *RequestContext
TracesData TracesData
FormatVersion uint32
}
var (
protoPoolTracesRequest = sync.Pool{
New: func() any {
return &TracesRequest{}
},
}
)
func NewTracesRequest() *TracesRequest {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &TracesRequest{}
}
return protoPoolTracesRequest.Get().(*TracesRequest)
}
func DeleteTracesRequest(orig *TracesRequest, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
DeleteRequestContext(orig.RequestContext, true)
DeleteTracesData(&orig.TracesData, false)
orig.Reset()
if nullable {
protoPoolTracesRequest.Put(orig)
}
}
func CopyTracesRequest(dest, src *TracesRequest) *TracesRequest {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewTracesRequest()
}
dest.RequestContext = CopyRequestContext(dest.RequestContext, src.RequestContext)
CopyTracesData(&dest.TracesData, &src.TracesData)
dest.FormatVersion = src.FormatVersion
return dest
}
func CopyTracesRequestSlice(dest, src []TracesRequest) []TracesRequest {
var newDest []TracesRequest
if cap(dest) < len(src) {
newDest = make([]TracesRequest, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteTracesRequest(&dest[i], false)
}
}
for i := range src {
CopyTracesRequest(&newDest[i], &src[i])
}
return newDest
}
func CopyTracesRequestPtrSlice(dest, src []*TracesRequest) []*TracesRequest {
var newDest []*TracesRequest
if cap(dest) < len(src) {
newDest = make([]*TracesRequest, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewTracesRequest()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteTracesRequest(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewTracesRequest()
}
}
for i := range src {
CopyTracesRequest(newDest[i], src[i])
}
return newDest
}
func (orig *TracesRequest) Reset() {
*orig = TracesRequest{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *TracesRequest) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.RequestContext != nil {
dest.WriteObjectField("requestContext")
orig.RequestContext.MarshalJSON(dest)
}
dest.WriteObjectField("tracesData")
orig.TracesData.MarshalJSON(dest)
if orig.FormatVersion != uint32(0) {
dest.WriteObjectField("formatVersion")
dest.WriteUint32(orig.FormatVersion)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *TracesRequest) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "requestContext", "request_context":
orig.RequestContext = NewRequestContext()
orig.RequestContext.UnmarshalJSON(iter)
case "tracesData", "traces_data":
orig.TracesData.UnmarshalJSON(iter)
case "formatVersion", "format_version":
orig.FormatVersion = iter.ReadUint32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *TracesRequest) SizeProto() int {
var n int
var l int
_ = l
if orig.RequestContext != nil {
l = orig.RequestContext.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
}
l = orig.TracesData.SizeProto()
n += 1 + proto.Sov(uint64(l)) + l
if orig.FormatVersion != uint32(0) {
n += 5
}
return n
}
func (orig *TracesRequest) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.RequestContext != nil {
l = orig.RequestContext.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
l = orig.TracesData.MarshalProto(buf[:pos])
pos -= l
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
if orig.FormatVersion != uint32(0) {
pos -= 4
binary.LittleEndian.PutUint32(buf[pos:], uint32(orig.FormatVersion))
pos--
buf[pos] = 0xd
}
return len(buf) - pos
}
func (orig *TracesRequest) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field RequestContext", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.RequestContext = NewRequestContext()
err = orig.RequestContext.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field TracesData", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
err = orig.TracesData.UnmarshalProto(buf[startPos:pos])
if err != nil {
return err
}
case 1:
if wireType != proto.WireTypeI32 {
return fmt.Errorf("proto: wrong wireType = %d for field FormatVersion", wireType)
}
var num uint32
num, pos, err = proto.ConsumeI32(buf, pos)
if err != nil {
return err
}
orig.FormatVersion = uint32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestTracesRequest() *TracesRequest {
orig := NewTracesRequest()
orig.RequestContext = GenTestRequestContext()
orig.TracesData = *GenTestTracesData()
orig.FormatVersion = uint32(13)
return orig
}
func GenTestTracesRequestPtrSlice() []*TracesRequest {
orig := make([]*TracesRequest, 5)
orig[0] = NewTracesRequest()
orig[1] = GenTestTracesRequest()
orig[2] = NewTracesRequest()
orig[3] = GenTestTracesRequest()
orig[4] = NewTracesRequest()
return orig
}
func GenTestTracesRequestSlice() []TracesRequest {
orig := make([]TracesRequest, 5)
orig[1] = *GenTestTracesRequest()
orig[3] = *GenTestTracesRequest()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type UDPAddr struct {
Zone string
IP []byte
Port int64
}
var (
protoPoolUDPAddr = sync.Pool{
New: func() any {
return &UDPAddr{}
},
}
)
func NewUDPAddr() *UDPAddr {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &UDPAddr{}
}
return protoPoolUDPAddr.Get().(*UDPAddr)
}
func DeleteUDPAddr(orig *UDPAddr, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolUDPAddr.Put(orig)
}
}
func CopyUDPAddr(dest, src *UDPAddr) *UDPAddr {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewUDPAddr()
}
dest.IP = src.IP
dest.Port = src.Port
dest.Zone = src.Zone
return dest
}
func CopyUDPAddrSlice(dest, src []UDPAddr) []UDPAddr {
var newDest []UDPAddr
if cap(dest) < len(src) {
newDest = make([]UDPAddr, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteUDPAddr(&dest[i], false)
}
}
for i := range src {
CopyUDPAddr(&newDest[i], &src[i])
}
return newDest
}
func CopyUDPAddrPtrSlice(dest, src []*UDPAddr) []*UDPAddr {
var newDest []*UDPAddr
if cap(dest) < len(src) {
newDest = make([]*UDPAddr, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewUDPAddr()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteUDPAddr(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewUDPAddr()
}
}
for i := range src {
CopyUDPAddr(newDest[i], src[i])
}
return newDest
}
func (orig *UDPAddr) Reset() {
*orig = UDPAddr{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *UDPAddr) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if len(orig.IP) > 0 {
dest.WriteObjectField("iP")
dest.WriteBytes(orig.IP)
}
if orig.Port != int64(0) {
dest.WriteObjectField("port")
dest.WriteInt64(orig.Port)
}
if orig.Zone != "" {
dest.WriteObjectField("zone")
dest.WriteString(orig.Zone)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *UDPAddr) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "iP":
orig.IP = iter.ReadBytes()
case "port":
orig.Port = iter.ReadInt64()
case "zone":
orig.Zone = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *UDPAddr) SizeProto() int {
var n int
var l int
_ = l
l = len(orig.IP)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
if orig.Port != int64(0) {
n += 1 + proto.Sov(uint64(orig.Port))
}
l = len(orig.Zone)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *UDPAddr) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = len(orig.IP)
if l > 0 {
pos -= l
copy(buf[pos:], orig.IP)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
if orig.Port != int64(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.Port))
pos--
buf[pos] = 0x10
}
l = len(orig.Zone)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Zone)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x1a
}
return len(buf) - pos
}
func (orig *UDPAddr) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field IP", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
if length != 0 {
orig.IP = make([]byte, length)
copy(orig.IP, buf[startPos:pos])
}
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field Port", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.Port = int64(num)
case 3:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Zone", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Zone = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestUDPAddr() *UDPAddr {
orig := NewUDPAddr()
orig.IP = []byte{1, 2, 3}
orig.Port = int64(13)
orig.Zone = "test_zone"
return orig
}
func GenTestUDPAddrPtrSlice() []*UDPAddr {
orig := make([]*UDPAddr, 5)
orig[0] = NewUDPAddr()
orig[1] = GenTestUDPAddr()
orig[2] = NewUDPAddr()
orig[3] = GenTestUDPAddr()
orig[4] = NewUDPAddr()
return orig
}
func GenTestUDPAddrSlice() []UDPAddr {
orig := make([]UDPAddr, 5)
orig[1] = *GenTestUDPAddr()
orig[3] = *GenTestUDPAddr()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
type UnixAddr struct {
Name string
Net string
}
var (
protoPoolUnixAddr = sync.Pool{
New: func() any {
return &UnixAddr{}
},
}
)
func NewUnixAddr() *UnixAddr {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &UnixAddr{}
}
return protoPoolUnixAddr.Get().(*UnixAddr)
}
func DeleteUnixAddr(orig *UnixAddr, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolUnixAddr.Put(orig)
}
}
func CopyUnixAddr(dest, src *UnixAddr) *UnixAddr {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewUnixAddr()
}
dest.Name = src.Name
dest.Net = src.Net
return dest
}
func CopyUnixAddrSlice(dest, src []UnixAddr) []UnixAddr {
var newDest []UnixAddr
if cap(dest) < len(src) {
newDest = make([]UnixAddr, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteUnixAddr(&dest[i], false)
}
}
for i := range src {
CopyUnixAddr(&newDest[i], &src[i])
}
return newDest
}
func CopyUnixAddrPtrSlice(dest, src []*UnixAddr) []*UnixAddr {
var newDest []*UnixAddr
if cap(dest) < len(src) {
newDest = make([]*UnixAddr, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewUnixAddr()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteUnixAddr(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewUnixAddr()
}
}
for i := range src {
CopyUnixAddr(newDest[i], src[i])
}
return newDest
}
func (orig *UnixAddr) Reset() {
*orig = UnixAddr{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *UnixAddr) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.Name != "" {
dest.WriteObjectField("name")
dest.WriteString(orig.Name)
}
if orig.Net != "" {
dest.WriteObjectField("net")
dest.WriteString(orig.Net)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *UnixAddr) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "name":
orig.Name = iter.ReadString()
case "net":
orig.Net = iter.ReadString()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *UnixAddr) SizeProto() int {
var n int
var l int
_ = l
l = len(orig.Name)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
l = len(orig.Net)
if l > 0 {
n += 1 + proto.Sov(uint64(l)) + l
}
return n
}
func (orig *UnixAddr) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
l = len(orig.Name)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Name)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0xa
}
l = len(orig.Net)
if l > 0 {
pos -= l
copy(buf[pos:], orig.Net)
pos = proto.EncodeVarint(buf, pos, uint64(l))
pos--
buf[pos] = 0x12
}
return len(buf) - pos
}
func (orig *UnixAddr) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Name = string(buf[startPos:pos])
case 2:
if wireType != proto.WireTypeLen {
return fmt.Errorf("proto: wrong wireType = %d for field Net", wireType)
}
var length int
length, pos, err = proto.ConsumeLen(buf, pos)
if err != nil {
return err
}
startPos := pos - length
orig.Net = string(buf[startPos:pos])
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestUnixAddr() *UnixAddr {
orig := NewUnixAddr()
orig.Name = "test_name"
orig.Net = "test_net"
return orig
}
func GenTestUnixAddrPtrSlice() []*UnixAddr {
orig := make([]*UnixAddr, 5)
orig[0] = NewUnixAddr()
orig[1] = GenTestUnixAddr()
orig[2] = NewUnixAddr()
orig[3] = GenTestUnixAddr()
orig[4] = NewUnixAddr()
return orig
}
func GenTestUnixAddrSlice() []UnixAddr {
orig := make([]UnixAddr, 5)
orig[1] = *GenTestUnixAddr()
orig[3] = *GenTestUnixAddr()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
import (
"fmt"
"sync"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/metadata"
"go.opentelemetry.io/collector/pdata/internal/proto"
)
// ValueType describes the type and units of a value.
type ValueType struct {
TypeStrindex int32
UnitStrindex int32
}
var (
protoPoolValueType = sync.Pool{
New: func() any {
return &ValueType{}
},
}
)
func NewValueType() *ValueType {
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
return &ValueType{}
}
return protoPoolValueType.Get().(*ValueType)
}
func DeleteValueType(orig *ValueType, nullable bool) {
if orig == nil {
return
}
if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {
orig.Reset()
return
}
orig.Reset()
if nullable {
protoPoolValueType.Put(orig)
}
}
func CopyValueType(dest, src *ValueType) *ValueType {
// If copying to same object, just return.
if src == dest {
return dest
}
if src == nil {
return nil
}
if dest == nil {
dest = NewValueType()
}
dest.TypeStrindex = src.TypeStrindex
dest.UnitStrindex = src.UnitStrindex
return dest
}
func CopyValueTypeSlice(dest, src []ValueType) []ValueType {
var newDest []ValueType
if cap(dest) < len(src) {
newDest = make([]ValueType, len(src))
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteValueType(&dest[i], false)
}
}
for i := range src {
CopyValueType(&newDest[i], &src[i])
}
return newDest
}
func CopyValueTypePtrSlice(dest, src []*ValueType) []*ValueType {
var newDest []*ValueType
if cap(dest) < len(src) {
newDest = make([]*ValueType, len(src))
// Copy old pointers to re-use.
copy(newDest, dest)
// Add new pointers for missing elements from len(dest) to len(srt).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewValueType()
}
} else {
newDest = dest[:len(src)]
// Cleanup the rest of the elements so GC can free the memory.
// This can happen when len(src) < len(dest) < cap(dest).
for i := len(src); i < len(dest); i++ {
DeleteValueType(dest[i], true)
dest[i] = nil
}
// Add new pointers for missing elements.
// This can happen when len(dest) < len(src) < cap(dest).
for i := len(dest); i < len(src); i++ {
newDest[i] = NewValueType()
}
}
for i := range src {
CopyValueType(newDest[i], src[i])
}
return newDest
}
func (orig *ValueType) Reset() {
*orig = ValueType{}
}
// MarshalJSON marshals all properties from the current struct to the destination stream.
func (orig *ValueType) MarshalJSON(dest *json.Stream) {
dest.WriteObjectStart()
if orig.TypeStrindex != int32(0) {
dest.WriteObjectField("typeStrindex")
dest.WriteInt32(orig.TypeStrindex)
}
if orig.UnitStrindex != int32(0) {
dest.WriteObjectField("unitStrindex")
dest.WriteInt32(orig.UnitStrindex)
}
dest.WriteObjectEnd()
}
// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.
func (orig *ValueType) UnmarshalJSON(iter *json.Iterator) {
for f := iter.ReadObject(); f != ""; f = iter.ReadObject() {
switch f {
case "typeStrindex", "type_strindex":
orig.TypeStrindex = iter.ReadInt32()
case "unitStrindex", "unit_strindex":
orig.UnitStrindex = iter.ReadInt32()
default:
iter.HandleUnknownField(f)
}
}
}
func (orig *ValueType) SizeProto() int {
var n int
var l int
_ = l
if orig.TypeStrindex != int32(0) {
n += 1 + proto.Sov(uint64(orig.TypeStrindex))
}
if orig.UnitStrindex != int32(0) {
n += 1 + proto.Sov(uint64(orig.UnitStrindex))
}
return n
}
func (orig *ValueType) MarshalProto(buf []byte) int {
pos := len(buf)
var l int
_ = l
if orig.TypeStrindex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.TypeStrindex))
pos--
buf[pos] = 0x8
}
if orig.UnitStrindex != int32(0) {
pos = proto.EncodeVarint(buf, pos, uint64(orig.UnitStrindex))
pos--
buf[pos] = 0x10
}
return len(buf) - pos
}
func (orig *ValueType) UnmarshalProto(buf []byte) error {
var err error
var fieldNum int32
var wireType proto.WireType
l := len(buf)
pos := 0
for pos < l {
// If in a group parsing, move to the next tag.
fieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)
if err != nil {
return err
}
switch fieldNum {
case 1:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field TypeStrindex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.TypeStrindex = int32(num)
case 2:
if wireType != proto.WireTypeVarint {
return fmt.Errorf("proto: wrong wireType = %d for field UnitStrindex", wireType)
}
var num uint64
num, pos, err = proto.ConsumeVarint(buf, pos)
if err != nil {
return err
}
orig.UnitStrindex = int32(num)
default:
pos, err = proto.ConsumeUnknown(buf, pos, wireType)
if err != nil {
return err
}
}
}
return nil
}
func GenTestValueType() *ValueType {
orig := NewValueType()
orig.TypeStrindex = int32(13)
orig.UnitStrindex = int32(13)
return orig
}
func GenTestValueTypePtrSlice() []*ValueType {
orig := make([]*ValueType, 5)
orig[0] = NewValueType()
orig[1] = GenTestValueType()
orig[2] = NewValueType()
orig[3] = GenTestValueType()
orig[4] = NewValueType()
return orig
}
func GenTestValueTypeSlice() []ValueType {
orig := make([]ValueType, 5)
orig[1] = *GenTestValueType()
orig[3] = *GenTestValueType()
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type SliceWrapper struct {
orig *[]AnyValue
state *State
}
func GetSliceOrig(ms SliceWrapper) *[]AnyValue {
return ms.orig
}
func GetSliceState(ms SliceWrapper) *State {
return ms.state
}
func NewSliceWrapper(orig *[]AnyValue, state *State) SliceWrapper {
return SliceWrapper{orig: orig, state: state}
}
func GenTestSliceWrapper() SliceWrapper {
orig := GenTestAnyValueSlice()
return NewSliceWrapper(&orig, NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type ByteSliceWrapper struct {
orig *[]byte
state *State
}
func GetByteSliceOrig(ms ByteSliceWrapper) *[]byte {
return ms.orig
}
func GetByteSliceState(ms ByteSliceWrapper) *State {
return ms.state
}
func NewByteSliceWrapper(orig *[]byte, state *State) ByteSliceWrapper {
return ByteSliceWrapper{orig: orig, state: state}
}
func GenTestByteSliceWrapper() ByteSliceWrapper {
orig := []byte{1, 2, 3}
return NewByteSliceWrapper(&orig, NewState())
}
func GenTestByteSlice() []byte {
return []byte{1, 2, 3}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type EntityRefWrapper struct {
orig *EntityRef
state *State
}
func GetEntityRefOrig(ms EntityRefWrapper) *EntityRef {
return ms.orig
}
func GetEntityRefState(ms EntityRefWrapper) *State {
return ms.state
}
func NewEntityRefWrapper(orig *EntityRef, state *State) EntityRefWrapper {
return EntityRefWrapper{orig: orig, state: state}
}
func GenTestEntityRefWrapper() EntityRefWrapper {
return NewEntityRefWrapper(GenTestEntityRef(), NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type EntityRefSliceWrapper struct {
orig *[]*EntityRef
state *State
}
func GetEntityRefSliceOrig(ms EntityRefSliceWrapper) *[]*EntityRef {
return ms.orig
}
func GetEntityRefSliceState(ms EntityRefSliceWrapper) *State {
return ms.state
}
func NewEntityRefSliceWrapper(orig *[]*EntityRef, state *State) EntityRefSliceWrapper {
return EntityRefSliceWrapper{orig: orig, state: state}
}
func GenTestEntityRefSliceWrapper() EntityRefSliceWrapper {
orig := GenTestEntityRefPtrSlice()
return NewEntityRefSliceWrapper(&orig, NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type LogsWrapper struct {
orig *ExportLogsServiceRequest
state *State
}
func GetLogsOrig(ms LogsWrapper) *ExportLogsServiceRequest {
return ms.orig
}
func GetLogsState(ms LogsWrapper) *State {
return ms.state
}
func NewLogsWrapper(orig *ExportLogsServiceRequest, state *State) LogsWrapper {
return LogsWrapper{orig: orig, state: state}
}
func GenTestLogsWrapper() LogsWrapper {
return NewLogsWrapper(GenTestExportLogsServiceRequest(), NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type MetricsWrapper struct {
orig *ExportMetricsServiceRequest
state *State
}
func GetMetricsOrig(ms MetricsWrapper) *ExportMetricsServiceRequest {
return ms.orig
}
func GetMetricsState(ms MetricsWrapper) *State {
return ms.state
}
func NewMetricsWrapper(orig *ExportMetricsServiceRequest, state *State) MetricsWrapper {
return MetricsWrapper{orig: orig, state: state}
}
func GenTestMetricsWrapper() MetricsWrapper {
return NewMetricsWrapper(GenTestExportMetricsServiceRequest(), NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type ProfilesWrapper struct {
orig *ExportProfilesServiceRequest
state *State
}
func GetProfilesOrig(ms ProfilesWrapper) *ExportProfilesServiceRequest {
return ms.orig
}
func GetProfilesState(ms ProfilesWrapper) *State {
return ms.state
}
func NewProfilesWrapper(orig *ExportProfilesServiceRequest, state *State) ProfilesWrapper {
return ProfilesWrapper{orig: orig, state: state}
}
func GenTestProfilesWrapper() ProfilesWrapper {
return NewProfilesWrapper(GenTestExportProfilesServiceRequest(), NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type TracesWrapper struct {
orig *ExportTraceServiceRequest
state *State
}
func GetTracesOrig(ms TracesWrapper) *ExportTraceServiceRequest {
return ms.orig
}
func GetTracesState(ms TracesWrapper) *State {
return ms.state
}
func NewTracesWrapper(orig *ExportTraceServiceRequest, state *State) TracesWrapper {
return TracesWrapper{orig: orig, state: state}
}
func GenTestTracesWrapper() TracesWrapper {
return NewTracesWrapper(GenTestExportTraceServiceRequest(), NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type Float64SliceWrapper struct {
orig *[]float64
state *State
}
func GetFloat64SliceOrig(ms Float64SliceWrapper) *[]float64 {
return ms.orig
}
func GetFloat64SliceState(ms Float64SliceWrapper) *State {
return ms.state
}
func NewFloat64SliceWrapper(orig *[]float64, state *State) Float64SliceWrapper {
return Float64SliceWrapper{orig: orig, state: state}
}
func GenTestFloat64SliceWrapper() Float64SliceWrapper {
orig := []float64{1.1, 2.2, 3.3}
return NewFloat64SliceWrapper(&orig, NewState())
}
func GenTestFloat64Slice() []float64 {
return []float64{1.1, 2.2, 3.3}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type InstrumentationScopeWrapper struct {
orig *InstrumentationScope
state *State
}
func GetInstrumentationScopeOrig(ms InstrumentationScopeWrapper) *InstrumentationScope {
return ms.orig
}
func GetInstrumentationScopeState(ms InstrumentationScopeWrapper) *State {
return ms.state
}
func NewInstrumentationScopeWrapper(orig *InstrumentationScope, state *State) InstrumentationScopeWrapper {
return InstrumentationScopeWrapper{orig: orig, state: state}
}
func GenTestInstrumentationScopeWrapper() InstrumentationScopeWrapper {
return NewInstrumentationScopeWrapper(GenTestInstrumentationScope(), NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type Int32SliceWrapper struct {
orig *[]int32
state *State
}
func GetInt32SliceOrig(ms Int32SliceWrapper) *[]int32 {
return ms.orig
}
func GetInt32SliceState(ms Int32SliceWrapper) *State {
return ms.state
}
func NewInt32SliceWrapper(orig *[]int32, state *State) Int32SliceWrapper {
return Int32SliceWrapper{orig: orig, state: state}
}
func GenTestInt32SliceWrapper() Int32SliceWrapper {
orig := []int32{1, 2, 3}
return NewInt32SliceWrapper(&orig, NewState())
}
func GenTestInt32Slice() []int32 {
return []int32{1, 2, 3}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type Int64SliceWrapper struct {
orig *[]int64
state *State
}
func GetInt64SliceOrig(ms Int64SliceWrapper) *[]int64 {
return ms.orig
}
func GetInt64SliceState(ms Int64SliceWrapper) *State {
return ms.state
}
func NewInt64SliceWrapper(orig *[]int64, state *State) Int64SliceWrapper {
return Int64SliceWrapper{orig: orig, state: state}
}
func GenTestInt64SliceWrapper() Int64SliceWrapper {
orig := []int64{1, 2, 3}
return NewInt64SliceWrapper(&orig, NewState())
}
func GenTestInt64Slice() []int64 {
return []int64{1, 2, 3}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type ProfilesDataWrapper struct {
orig *ProfilesData
state *State
}
func GetProfilesDataOrig(ms ProfilesDataWrapper) *ProfilesData {
return ms.orig
}
func GetProfilesDataState(ms ProfilesDataWrapper) *State {
return ms.state
}
func NewProfilesDataWrapper(orig *ProfilesData, state *State) ProfilesDataWrapper {
return ProfilesDataWrapper{orig: orig, state: state}
}
func GenTestProfilesDataWrapper() ProfilesDataWrapper {
return NewProfilesDataWrapper(GenTestProfilesData(), NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type ResourceWrapper struct {
orig *Resource
state *State
}
func GetResourceOrig(ms ResourceWrapper) *Resource {
return ms.orig
}
func GetResourceState(ms ResourceWrapper) *State {
return ms.state
}
func NewResourceWrapper(orig *Resource, state *State) ResourceWrapper {
return ResourceWrapper{orig: orig, state: state}
}
func GenTestResourceWrapper() ResourceWrapper {
return NewResourceWrapper(GenTestResource(), NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type StringSliceWrapper struct {
orig *[]string
state *State
}
func GetStringSliceOrig(ms StringSliceWrapper) *[]string {
return ms.orig
}
func GetStringSliceState(ms StringSliceWrapper) *State {
return ms.state
}
func NewStringSliceWrapper(orig *[]string, state *State) StringSliceWrapper {
return StringSliceWrapper{orig: orig, state: state}
}
func GenTestStringSliceWrapper() StringSliceWrapper {
orig := []string{"a", "b", "c"}
return NewStringSliceWrapper(&orig, NewState())
}
func GenTestStringSlice() []string {
return []string{"a", "b", "c"}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package internal
type UInt64SliceWrapper struct {
orig *[]uint64
state *State
}
func GetUInt64SliceOrig(ms UInt64SliceWrapper) *[]uint64 {
return ms.orig
}
func GetUInt64SliceState(ms UInt64SliceWrapper) *State {
return ms.state
}
func NewUInt64SliceWrapper(orig *[]uint64, state *State) UInt64SliceWrapper {
return UInt64SliceWrapper{orig: orig, state: state}
}
func GenTestUInt64SliceWrapper() UInt64SliceWrapper {
orig := []uint64{1, 2, 3}
return NewUInt64SliceWrapper(&orig, NewState())
}
func GenTestUint64Slice() []uint64 {
return []uint64{1, 2, 3}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package json // import "go.opentelemetry.io/collector/pdata/internal/json"
import (
"encoding/base64"
"strconv"
jsoniter "github.com/json-iterator/go"
)
func BorrowIterator(data []byte) *Iterator {
return &Iterator{
delegate: jsoniter.ConfigFastest.BorrowIterator(data),
}
}
func ReturnIterator(s *Iterator) {
jsoniter.ConfigFastest.ReturnIterator(s.delegate)
}
type Iterator struct {
delegate *jsoniter.Iterator
disallowUnknownFields bool
}
// SetDisallowUnknownFields configures whether unknown fields encountered during
// JSON unmarshalling cause an error. When set to true, [Iterator.HandleUnknownField]
// records an error instead of skipping the field.
func (iter *Iterator) SetDisallowUnknownFields(b bool) *Iterator {
iter.disallowUnknownFields = b
return iter
}
// HandleUnknownField is called by generated UnmarshalJSON code when an
// unrecognized JSON field is encountered. By default the field's value is
// skipped, but if [Iterator.SetDisallowUnknownFields] was set to true, an
// error is recorded on the iterator instead.
func (iter *Iterator) HandleUnknownField(field string) {
if iter.disallowUnknownFields {
iter.ReportError("UnmarshalJSON", "unknown field \""+field+"\"")
return
}
iter.Skip()
}
// ReadInt32 unmarshalls JSON data into an int32. Accepts both numbers and strings decimal.
// See https://developers.google.com/protocol-buffers/docs/proto3#json.
func (iter *Iterator) ReadInt32() int32 {
switch iter.delegate.WhatIsNext() {
case jsoniter.NumberValue:
return iter.delegate.ReadInt32()
case jsoniter.StringValue:
val, err := strconv.ParseInt(iter.ReadString(), 10, 32)
if err != nil {
iter.ReportError("ReadInt32", err.Error())
return 0
}
return int32(val)
default:
iter.ReportError("ReadInt32", "unsupported value type")
return 0
}
}
// ReadUint32 unmarshalls JSON data into an uint32. Accepts both numbers and strings decimal.
// See https://developers.google.com/protocol-buffers/docs/proto3#json.
func (iter *Iterator) ReadUint32() uint32 {
switch iter.delegate.WhatIsNext() {
case jsoniter.NumberValue:
return iter.delegate.ReadUint32()
case jsoniter.StringValue:
val, err := strconv.ParseUint(iter.ReadString(), 10, 32)
if err != nil {
iter.ReportError("ReadUint32", err.Error())
return 0
}
return uint32(val)
default:
iter.ReportError("ReadUint32", "unsupported value type")
return 0
}
}
// ReadInt64 unmarshalls JSON data into an int64. Accepts both numbers and strings decimal.
// See https://developers.google.com/protocol-buffers/docs/proto3#json.
func (iter *Iterator) ReadInt64() int64 {
switch iter.delegate.WhatIsNext() {
case jsoniter.NumberValue:
return iter.delegate.ReadInt64()
case jsoniter.StringValue:
val, err := strconv.ParseInt(iter.ReadString(), 10, 64)
if err != nil {
iter.ReportError("ReadInt64", err.Error())
return 0
}
return val
default:
iter.ReportError("ReadInt64", "unsupported value type")
return 0
}
}
// ReadUint64 unmarshalls JSON data into an uint64. Accepts both numbers and strings decimal.
// See https://developers.google.com/protocol-buffers/docs/proto3#json.
func (iter *Iterator) ReadUint64() uint64 {
switch iter.delegate.WhatIsNext() {
case jsoniter.NumberValue:
return iter.delegate.ReadUint64()
case jsoniter.StringValue:
val, err := strconv.ParseUint(iter.ReadString(), 10, 64)
if err != nil {
iter.ReportError("ReadUint64", err.Error())
return 0
}
return val
default:
iter.ReportError("ReadUint64", "unsupported value type")
return 0
}
}
func (iter *Iterator) ReadFloat32() float32 {
switch iter.delegate.WhatIsNext() {
case jsoniter.NumberValue:
return iter.delegate.ReadFloat32()
case jsoniter.StringValue:
val, err := strconv.ParseFloat(iter.ReadString(), 32)
if err != nil {
iter.ReportError("ReadUint64", err.Error())
return 0
}
return float32(val)
default:
iter.ReportError("ReadUint64", "unsupported value type")
return 0
}
}
func (iter *Iterator) ReadFloat64() float64 {
switch iter.delegate.WhatIsNext() {
case jsoniter.NumberValue:
return iter.delegate.ReadFloat64()
case jsoniter.StringValue:
val, err := strconv.ParseFloat(iter.ReadString(), 64)
if err != nil {
iter.ReportError("ReadUint64", err.Error())
return 0
}
return val
default:
iter.ReportError("ReadUint64", "unsupported value type")
return 0
}
}
// ReadBool reads a json object as BoolValue
func (iter *Iterator) ReadBool() bool {
return iter.delegate.ReadBool()
}
// ReadString read string from iterator
func (iter *Iterator) ReadString() string {
return iter.delegate.ReadString()
}
// ReadBytes read base64 encoded bytes from iterator.
func (iter *Iterator) ReadBytes() []byte {
buf := iter.ReadStringAsSlice()
if len(buf) == 0 {
return nil
}
orig := make([]byte, base64.StdEncoding.DecodedLen(len(buf)))
n, err := base64.StdEncoding.Decode(orig, buf)
if err != nil {
iter.ReportError("base64.Decode", err.Error())
}
return orig[:n]
}
// ReadStringAsSlice read string from iterator without copying into string form.
// The []byte cannot be kept, as it will change after next iterator call.
func (iter *Iterator) ReadStringAsSlice() []byte {
return iter.delegate.ReadStringAsSlice()
}
// ReportError record a error in iterator instance with current position.
func (iter *Iterator) ReportError(operation, msg string) {
iter.delegate.ReportError(operation, msg)
}
// Error returns any recorded error if any otherwise it returns nil.
func (iter *Iterator) Error() error {
return iter.delegate.Error
}
// Skip skips a json object and positions to relatively the next json object
func (iter *Iterator) Skip() {
iter.delegate.Skip()
}
// ReadArray read array element, returns true if the array has more element to read.
func (iter *Iterator) ReadArray() bool {
return iter.delegate.ReadArray()
}
// ReadObject read one field from object.
// If object ended, returns empty string. Otherwise, returns the field name.
func (iter *Iterator) ReadObject() string {
return iter.delegate.ReadObject()
}
// ReadEnumValue returns the enum integer value representation. Accepts both enum names and enum integer values.
// See https://developers.google.com/protocol-buffers/docs/proto3#json.
func (iter *Iterator) ReadEnumValue(valueMap map[string]int32) int32 {
switch iter.delegate.WhatIsNext() {
case jsoniter.NumberValue:
return iter.ReadInt32()
case jsoniter.StringValue:
val, ok := valueMap[iter.ReadString()]
// Same behavior with official protobuf JSON decoder,
// see https://github.com/open-telemetry/opentelemetry-proto-go/pull/81
if !ok {
iter.ReportError("ReadEnumValue", "unknown string value")
return 0
}
return val
default:
iter.ReportError("ReadEnumValue", "unsupported value type")
return 0
}
}
// ResetBytes reuse iterator instance by specifying another byte array as input
func (iter *Iterator) ResetBytes(input []byte) *Iterator {
iter.delegate.ResetBytes(input)
return iter
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package json // import "go.opentelemetry.io/collector/pdata/internal/json"
import (
"encoding/base64"
"errors"
"io"
"math"
"strconv"
jsoniter "github.com/json-iterator/go"
)
func BorrowStream(writer io.Writer) *Stream {
return &Stream{
Stream: jsoniter.ConfigFastest.BorrowStream(writer),
wmTracker: make([]bool, 32),
}
}
func ReturnStream(s *Stream) {
jsoniter.ConfigFastest.ReturnStream(s.Stream)
}
// Stream avoids the need to explicitly call the `Stream.WriteMore` method while marshaling objects by
// checking if a field was previously written inside the current object and automatically appending a ","
// if so before writing the next field.
type Stream struct {
*jsoniter.Stream
// wmTracker acts like a stack which pushes a new value when an object is started and removes the
// top when it is ended. The value added for every object tracks if there is any written field
// already for that object, and if it is then automatically add a "," before any new field.
wmTracker []bool
}
func (ots *Stream) WriteObjectStart() {
ots.Stream.WriteObjectStart()
ots.wmTracker = append(ots.wmTracker, false)
}
func (ots *Stream) WriteObjectField(field string) {
if ots.wmTracker[len(ots.wmTracker)-1] {
ots.WriteMore()
}
ots.Stream.WriteObjectField(field)
ots.wmTracker[len(ots.wmTracker)-1] = true
}
func (ots *Stream) WriteObjectEnd() {
ots.Stream.WriteObjectEnd()
ots.wmTracker = ots.wmTracker[:len(ots.wmTracker)-1]
}
// WriteInt64 writes the values as a decimal string. This is per the protobuf encoding rules for int64, fixed64, uint64.
func (ots *Stream) WriteInt64(val int64) {
// 19 digits + optional leading '-' + 2 quotes = 22 bytes maximum.
var buf [22]byte
buf[0] = '"'
b := strconv.AppendInt(buf[1:1], val, 10)
n := 1 + len(b)
buf[n] = '"'
_, _ = ots.Write(buf[:n+1])
}
// WriteUint64 writes the values as a decimal string. This is per the protobuf encoding rules for int64, fixed64, uint64.
func (ots *Stream) WriteUint64(val uint64) {
// 20 digits + 2 quotes = 22 bytes maximum.
var buf [22]byte
buf[0] = '"'
b := strconv.AppendUint(buf[1:1], val, 10)
n := 1 + len(b)
buf[n] = '"'
_, _ = ots.Write(buf[:n+1])
}
// WriteBytes writes the values as a base64 encoded string. This is per the protobuf encoding rules for bytes.
func (ots *Stream) WriteBytes(val []byte) {
if len(val) == 0 {
ots.WriteString("")
return
}
ots.WriteString(base64.StdEncoding.EncodeToString(val))
}
// WriteFloat64 writes the JSON value that will be a number or one of the special string
// values "NaN", "Infinity", and "-Infinity". Either numbers or strings are accepted.
// Empty strings are invalid. Exponent notation is also accepted.
// See https://protobuf.dev/programming-guides/json/.
func (ots *Stream) WriteFloat64(val float64) {
if math.IsNaN(val) {
ots.WriteString("NaN")
return
}
if math.IsInf(val, 1) {
ots.WriteString("Infinity")
return
}
if math.IsInf(val, -1) {
ots.WriteString("-Infinity")
return
}
ots.Stream.WriteFloat64(val)
}
func (ots *Stream) ReportError(err error) {
ots.Stream.Error = errors.Join(ots.Stream.Error, err)
}
func (ots *Stream) Error() error {
return ots.Stream.Error
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otelgrpc // import "go.opentelemetry.io/collector/pdata/internal/otelgrpc"
import (
"google.golang.org/grpc/encoding"
"google.golang.org/grpc/mem"
)
var (
defaultBufferPoolSizes = []int{
256,
4 << 10, // 4KB (go page size)
16 << 10, // 16KB (max HTTP/2 frame size used by gRPC)
32 << 10, // 32KB (default buffer size for io.Copy)
64 << 10, // 64KB
128 << 10, // 128KB
256 << 10, // 256KB
512 << 10, // 512KB
1 << 20, // 1MB
4 << 20, // 4MB
16 << 20, // 16MB
}
otelBufferPool = mem.NewTieredBufferPool(defaultBufferPoolSizes...)
)
// DefaultBufferPool returns the current default buffer pool. It is a BufferPool
// created with mem.NewTieredBufferPool that uses a set of default sizes optimized for
// expected telemetry workflows.
func DefaultBufferPool() mem.BufferPool {
return otelBufferPool
}
// Name is the name registered for the proto compressor.
const Name = "proto"
func init() {
encoding.RegisterCodecV2(&codecV2{delegate: encoding.GetCodecV2(Name)})
}
// codecV2 is a custom proto encoding that uses a different tier schema for the TieredBufferPool as well
// as it call into the custom marshal/unmarshal logic that works with memory pooling.
// If not an otlp payload fallback on the default grpc/proto encoding.
type codecV2 struct {
delegate encoding.CodecV2
}
type otelEncoder interface {
SizeProto() int
MarshalProto([]byte) int
UnmarshalProto([]byte) error
}
func (c *codecV2) Marshal(v any) (mem.BufferSlice, error) {
if m, ok := v.(otelEncoder); ok {
size := m.SizeProto()
buf := otelBufferPool.Get(size)
n := m.MarshalProto((*buf)[:size])
*buf = (*buf)[:n]
return []mem.Buffer{mem.NewBuffer(buf, otelBufferPool)}, nil
}
return c.delegate.Marshal(v)
}
func (c *codecV2) Unmarshal(data mem.BufferSlice, v any) (err error) {
if m, ok := v.(otelEncoder); ok {
// TODO: Upgrade custom Unmarshal logic to support reading from mem.BufferSlice.
buf := data.MaterializeToBuffer(otelBufferPool)
defer buf.Free()
return m.UnmarshalProto(buf.ReadOnlyData())
}
return c.delegate.Unmarshal(data, v)
}
func (c *codecV2) Name() string {
return Name
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otelgrpc // import "go.opentelemetry.io/collector/pdata/internal/otelgrpc"
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"go.opentelemetry.io/collector/pdata/internal"
)
// LogsServiceClient is the client API for LogsService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type LogsServiceClient interface {
Export(context.Context, *internal.ExportLogsServiceRequest, ...grpc.CallOption) (*internal.ExportLogsServiceResponse, error)
}
type logsServiceClient struct {
cc *grpc.ClientConn
}
func NewLogsServiceClient(cc *grpc.ClientConn) LogsServiceClient {
return &logsServiceClient{cc}
}
func (c *logsServiceClient) Export(ctx context.Context, in *internal.ExportLogsServiceRequest, opts ...grpc.CallOption) (*internal.ExportLogsServiceResponse, error) {
out := new(internal.ExportLogsServiceResponse)
err := c.cc.Invoke(ctx, "/opentelemetry.proto.collector.logs.v1.LogsService/Export", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// LogsServiceServer is the server API for LogsService service.
type LogsServiceServer interface {
Export(context.Context, *internal.ExportLogsServiceRequest) (*internal.ExportLogsServiceResponse, error)
}
// UnimplementedLogsServiceServer can be embedded to have forward compatible implementations.
type UnimplementedLogsServiceServer struct{}
func (*UnimplementedLogsServiceServer) Export(context.Context, *internal.ExportLogsServiceRequest) (*internal.ExportLogsServiceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Export not implemented")
}
func RegisterLogsServiceServer(s *grpc.Server, srv LogsServiceServer) {
s.RegisterService(&logsServiceServiceDesc, srv)
}
// Context cannot be the first parameter of the function because gRPC definition.
//
//nolint:revive
func logsServiceExportHandler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
in := internal.NewExportLogsServiceRequest()
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LogsServiceServer).Export(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/opentelemetry.proto.collector.logs.v1.LogsService/Export",
}
handler := func(ctx context.Context, req any) (any, error) {
return srv.(LogsServiceServer).Export(ctx, req.(*internal.ExportLogsServiceRequest))
}
return interceptor(ctx, in, info, handler)
}
var logsServiceServiceDesc = grpc.ServiceDesc{
ServiceName: "opentelemetry.proto.collector.logs.v1.LogsService",
HandlerType: (*LogsServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Export",
Handler: logsServiceExportHandler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "opentelemetry/proto/collector/logs/v1/logs_service.proto",
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otelgrpc // import "go.opentelemetry.io/collector/pdata/internal/otelgrpc"
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"go.opentelemetry.io/collector/pdata/internal"
)
// MetricsServiceClient is the client API for MetricsService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type MetricsServiceClient interface {
Export(context.Context, *internal.ExportMetricsServiceRequest, ...grpc.CallOption) (*internal.ExportMetricsServiceResponse, error)
}
type metricsServiceClient struct {
cc *grpc.ClientConn
}
func NewMetricsServiceClient(cc *grpc.ClientConn) MetricsServiceClient {
return &metricsServiceClient{cc}
}
func (c *metricsServiceClient) Export(ctx context.Context, in *internal.ExportMetricsServiceRequest, opts ...grpc.CallOption) (*internal.ExportMetricsServiceResponse, error) {
out := new(internal.ExportMetricsServiceResponse)
err := c.cc.Invoke(ctx, "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// MetricsServiceServer is the server API for MetricsService service.
type MetricsServiceServer interface {
Export(context.Context, *internal.ExportMetricsServiceRequest) (*internal.ExportMetricsServiceResponse, error)
}
// UnimplementedMetricsServiceServer can be embedded to have forward compatible implementations.
type UnimplementedMetricsServiceServer struct{}
func (*UnimplementedMetricsServiceServer) Export(context.Context, *internal.ExportMetricsServiceRequest) (*internal.ExportMetricsServiceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Export not implemented")
}
func RegisterMetricsServiceServer(s *grpc.Server, srv MetricsServiceServer) {
s.RegisterService(&metricsServiceServiceDesc, srv)
}
// Context cannot be the first parameter of the function because gRPC definition.
//
//nolint:revive
func metricsServiceExportHandler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
in := internal.NewExportMetricsServiceRequest()
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MetricsServiceServer).Export(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export",
}
handler := func(ctx context.Context, req any) (any, error) {
return srv.(MetricsServiceServer).Export(ctx, req.(*internal.ExportMetricsServiceRequest))
}
return interceptor(ctx, in, info, handler)
}
var metricsServiceServiceDesc = grpc.ServiceDesc{
ServiceName: "opentelemetry.proto.collector.metrics.v1.MetricsService",
HandlerType: (*MetricsServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Export",
Handler: metricsServiceExportHandler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "opentelemetry/proto/collector/metrics/v1/metrics_service.proto",
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otelgrpc // import "go.opentelemetry.io/collector/pdata/internal/otelgrpc"
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/internal/otlp"
)
// ProfilesServiceClient is the client API for ProfilesService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type ProfilesServiceClient interface {
Export(context.Context, *internal.ExportProfilesServiceRequest, ...grpc.CallOption) (*internal.ExportProfilesServiceResponse, error)
}
type profilesServiceClient struct {
cc *grpc.ClientConn
}
func NewProfilesServiceClient(cc *grpc.ClientConn) ProfilesServiceClient {
return &profilesServiceClient{cc}
}
func (c *profilesServiceClient) Export(ctx context.Context, in *internal.ExportProfilesServiceRequest, opts ...grpc.CallOption) (*internal.ExportProfilesServiceResponse, error) {
out := new(internal.ExportProfilesServiceResponse)
err := c.cc.Invoke(ctx, "/opentelemetry.proto.collector.profiles.v1development.ProfilesService/Export", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// ProfilesServiceServer is the server API for ProfilesService service.
type ProfilesServiceServer interface {
Export(context.Context, *internal.ExportProfilesServiceRequest) (*internal.ExportProfilesServiceResponse, error)
}
// UnimplementedProfilesServiceServer can be embedded to have forward compatible implementations.
type UnimplementedProfilesServiceServer struct{}
func (*UnimplementedProfilesServiceServer) Export(context.Context, *internal.ExportProfilesServiceRequest) (*internal.ExportProfilesServiceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Export not implemented")
}
func RegisterProfilesServiceServer(s *grpc.Server, srv ProfilesServiceServer) {
s.RegisterService(&profilesServiceServiceDesc, srv)
}
// Context cannot be the first parameter of the function because gRPC definition.
//
//nolint:revive
func profilesServiceExportHandler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
// Unary interceptors run after dec, so validate the version here to reject
// incompatible payloads before protobuf deserialization.
if err := otlp.ValidateProfilesDevelopmentVersion(metadata.ValueFromIncomingContext(ctx, otlp.ProfilesDevelopmentVersionHeader)); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
in := internal.NewExportProfilesServiceRequest()
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ProfilesServiceServer).Export(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/opentelemetry.proto.collector.profiles.v1development.ProfilesService/Export",
}
handler := func(ctx context.Context, req any) (any, error) {
return srv.(ProfilesServiceServer).Export(ctx, req.(*internal.ExportProfilesServiceRequest))
}
return interceptor(ctx, in, info, handler)
}
var profilesServiceServiceDesc = grpc.ServiceDesc{
ServiceName: "opentelemetry.proto.collector.profiles.v1development.ProfilesService",
HandlerType: (*ProfilesServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Export",
Handler: profilesServiceExportHandler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "opentelemetry/proto/collector/profiles/v1development/profiles_service.proto",
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otelgrpc // import "go.opentelemetry.io/collector/pdata/internal/otelgrpc"
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"go.opentelemetry.io/collector/pdata/internal"
)
// TraceServiceClient is the client API for TraceService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type TraceServiceClient interface {
Export(context.Context, *internal.ExportTraceServiceRequest, ...grpc.CallOption) (*internal.ExportTraceServiceResponse, error)
}
type traceServiceClient struct {
cc *grpc.ClientConn
}
func NewTraceServiceClient(cc *grpc.ClientConn) TraceServiceClient {
return &traceServiceClient{cc}
}
func (c *traceServiceClient) Export(ctx context.Context, in *internal.ExportTraceServiceRequest, opts ...grpc.CallOption) (*internal.ExportTraceServiceResponse, error) {
out := new(internal.ExportTraceServiceResponse)
err := c.cc.Invoke(ctx, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// TraceServiceServer is the server API for TraceService service.
type TraceServiceServer interface {
Export(context.Context, *internal.ExportTraceServiceRequest) (*internal.ExportTraceServiceResponse, error)
}
// UnimplementedTraceServiceServer can be embedded to have forward compatible implementations.
type UnimplementedTraceServiceServer struct{}
func (*UnimplementedTraceServiceServer) Export(context.Context, *internal.ExportTraceServiceRequest) (*internal.ExportTraceServiceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Export not implemented")
}
func RegisterTraceServiceServer(s *grpc.Server, srv TraceServiceServer) {
s.RegisterService(&traceServiceServiceDesc, srv)
}
// Context cannot be the first parameter of the function because gRPC definition.
//
//nolint:revive
func traceServiceExportHandler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
in := internal.NewExportTraceServiceRequest()
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TraceServiceServer).Export(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/opentelemetry.proto.collector.trace.v1.TraceService/Export",
}
handler := func(ctx context.Context, req any) (any, error) {
return srv.(TraceServiceServer).Export(ctx, req.(*internal.ExportTraceServiceRequest))
}
return interceptor(ctx, in, info, handler)
}
var traceServiceServiceDesc = grpc.ServiceDesc{
ServiceName: "opentelemetry.proto.collector.trace.v1.TraceService",
HandlerType: (*TraceServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Export",
Handler: traceServiceExportHandler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "opentelemetry/proto/collector/trace/v1/trace_service.proto",
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlp // import "go.opentelemetry.io/collector/pdata/internal/otlp"
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// MigrateLogs implements any translation needed due to deprecation in OTLP logs protocol.
// Any plog.Unmarshaler implementation from OTLP (proto/json) MUST call this, and the gRPC Server implementation.
func MigrateLogs(rls []*internal.ResourceLogs) {
for _, rl := range rls {
if len(rl.ScopeLogs) == 0 {
rl.ScopeLogs = rl.DeprecatedScopeLogs
}
rl.DeprecatedScopeLogs = nil
}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlp // import "go.opentelemetry.io/collector/pdata/internal/otlp"
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// MigrateMetrics implements any translation needed due to deprecation in OTLP metrics protocol.
// Any pmetric.Unmarshaler implementation from OTLP (proto/json) MUST call this, and the gRPC Server implementation.
func MigrateMetrics(rms []*internal.ResourceMetrics) {
for _, rm := range rms {
if len(rm.ScopeMetrics) == 0 {
rm.ScopeMetrics = rm.DeprecatedScopeMetrics
}
rm.DeprecatedScopeMetrics = nil
}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlp // import "go.opentelemetry.io/collector/pdata/internal/otlp"
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// MigrateProfiles implements any translation needed due to deprecation in OTLP profiles protocol.
// Any pprofile.Unmarshaler implementation from OTLP (proto/json) MUST call this, and the gRPC Server implementation.
func MigrateProfiles(_ []*internal.ResourceProfiles) {}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlp // import "go.opentelemetry.io/collector/pdata/internal/otlp"
import (
"errors"
"fmt"
"go.opentelemetry.io/collector/pdata/internal"
)
var errProfilesStringIndexNotInitialized = errors.New("profiles dictionary string index is not initialized")
// ConvertProfilesToReferences interns resource and scope attribute strings in
// the profiles dictionary. The request must be mutable.
func ConvertProfilesToReferences(request *internal.ExportProfilesServiceRequest) error {
stringTable := &request.Dictionary.StringTable
if len(*stringTable) == 0 {
// string_table[0] is the required empty-string sentinel.
*stringTable = append(*stringTable, "")
}
stringIndex := make(map[string]int32, len(*stringTable))
for i, value := range *stringTable {
if i == 0 && value != "" {
// Preserve existing dictionary indices without using the reserved
// zero index for a new attribute key.
continue
}
// Keep the first occurrence so the required empty string resolves to
// the canonical index 0 even if the table already contains duplicates.
if _, ok := stringIndex[value]; !ok {
stringIndex[value] = int32(i)
}
}
getStringIndex := func(s string) (int32, error) {
if stringIndex == nil {
return 0, errProfilesStringIndexNotInitialized
}
if index, ok := stringIndex[s]; ok {
return index, nil
}
index := int32(len(*stringTable))
*stringTable = append(*stringTable, s)
stringIndex[s] = index
return index, nil
}
for resourceIndex, resourceProfiles := range request.ResourceProfiles {
if err := ConvertProfilesKeyValuesToReferences(getStringIndex, resourceProfiles.Resource.Attributes); err != nil {
return fmt.Errorf("resource profiles %d resource attributes: %w", resourceIndex, err)
}
for scopeIndex, scopeProfiles := range resourceProfiles.ScopeProfiles {
if err := ConvertProfilesKeyValuesToReferences(getStringIndex, scopeProfiles.Scope.Attributes); err != nil {
return fmt.Errorf("resource profiles %d scope profiles %d attributes: %w", resourceIndex, scopeIndex, err)
}
}
}
return nil
}
// ResolveProfilesReferences resolves resource and scope attribute string-table
// references so pdata consumers can access the attributes transparently.
func ResolveProfilesReferences(request *internal.ExportProfilesServiceRequest) error {
stringTable := request.Dictionary.StringTable
for resourceIndex, resourceProfiles := range request.ResourceProfiles {
if err := ResolveProfilesKeyValueReferences(stringTable, resourceProfiles.Resource.Attributes); err != nil {
return fmt.Errorf("resource profiles %d resource attributes: %w", resourceIndex, err)
}
for scopeIndex, scopeProfiles := range resourceProfiles.ScopeProfiles {
if err := ResolveProfilesKeyValueReferences(stringTable, scopeProfiles.Scope.Attributes); err != nil {
return fmt.Errorf("resource profiles %d scope profiles %d attributes: %w", resourceIndex, scopeIndex, err)
}
}
}
return nil
}
// ConvertProfilesKeyValuesToReferences converts attribute strings to dictionary references.
func ConvertProfilesKeyValuesToReferences(getStringIndex func(string) (int32, error), keyValues []internal.KeyValue) error {
for i := range keyValues {
keyValue := &keyValues[i]
if keyValue.Key != "" && keyValue.KeyStrindex != 0 {
return fmt.Errorf("attribute %d has both key and key_strindex set", i)
}
if keyValue.Key != "" {
index, err := getStringIndex(keyValue.Key)
if err != nil {
return err
}
keyValue.KeyStrindex = index
keyValue.Key = ""
}
if err := ConvertProfilesAnyValueToReference(getStringIndex, &keyValue.Value); err != nil {
return err
}
}
return nil
}
// ConvertProfilesAnyValueToReference converts strings recursively in an attribute value.
func ConvertProfilesAnyValueToReference(getStringIndex func(string) (int32, error), value *internal.AnyValue) error {
switch original := value.Value.(type) {
case *internal.AnyValue_StringValueStrindex:
return nil
case *internal.AnyValue_StringValue:
index, err := getStringIndex(original.StringValue)
if err != nil {
return err
}
reference := internal.NewAnyValue_StringValueStrindex()
reference.StringValueStrindex = index
value.Value = reference
case *internal.AnyValue_KvlistValue:
if original.KvlistValue != nil {
return ConvertProfilesKeyValuesToReferences(getStringIndex, original.KvlistValue.Values)
}
case *internal.AnyValue_ArrayValue:
if original.ArrayValue != nil {
for i := range original.ArrayValue.Values {
if err := ConvertProfilesAnyValueToReference(getStringIndex, &original.ArrayValue.Values[i]); err != nil {
return err
}
}
}
}
return nil
}
// ResolveProfilesKeyValueReferences resolves attribute dictionary references.
func ResolveProfilesKeyValueReferences(stringTable []string, keyValues []internal.KeyValue) error {
for i := range keyValues {
keyValue := &keyValues[i]
if keyValue.Key != "" && keyValue.KeyStrindex != 0 {
return fmt.Errorf("attribute %d has both key and key_strindex set", i)
}
if keyValue.KeyStrindex < 0 || (keyValue.KeyStrindex > 0 && int(keyValue.KeyStrindex) >= len(stringTable)) {
return fmt.Errorf("attribute %d has invalid key_strindex %d", i, keyValue.KeyStrindex)
}
if keyValue.KeyStrindex > 0 {
keyValue.Key = stringTable[keyValue.KeyStrindex]
keyValue.KeyStrindex = 0
}
if err := ResolveProfilesAnyValueReference(stringTable, &keyValue.Value); err != nil {
return fmt.Errorf("attribute %d value: %w", i, err)
}
}
return nil
}
// ResolveProfilesAnyValueReference resolves string references recursively in an attribute value.
func ResolveProfilesAnyValueReference(stringTable []string, value *internal.AnyValue) error {
switch original := value.Value.(type) {
case *internal.AnyValue_StringValueStrindex:
if original.StringValueStrindex < 0 || int(original.StringValueStrindex) >= len(stringTable) {
return fmt.Errorf("invalid string_value_strindex %d", original.StringValueStrindex)
}
resolved := internal.NewAnyValue_StringValue()
resolved.StringValue = stringTable[original.StringValueStrindex]
value.Value = resolved
case *internal.AnyValue_KvlistValue:
if original.KvlistValue != nil {
return ResolveProfilesKeyValueReferences(stringTable, original.KvlistValue.Values)
}
case *internal.AnyValue_ArrayValue:
if original.ArrayValue != nil {
for i := range original.ArrayValue.Values {
if err := ResolveProfilesAnyValueReference(stringTable, &original.ArrayValue.Values[i]); err != nil {
return fmt.Errorf("array value %d: %w", i, err)
}
}
}
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlp // import "go.opentelemetry.io/collector/pdata/internal/otlp"
import "fmt"
// ProfilesDevelopmentVersion is the version of the Profiles schema compiled into pdata.
// Update it when adopting an incompatible schema change from opentelemetry-proto.
const ProfilesDevelopmentVersion = "1"
// ProfilesDevelopmentVersionHeader is the OTLP Profiles development version metadata key.
const ProfilesDevelopmentVersionHeader = "otlp-profiles-development-version"
// ValidateProfilesDevelopmentVersion checks all values of the request metadata.
// Missing metadata identifies version 1, including after pdata adopts a later version.
func ValidateProfilesDevelopmentVersion(values []string) error {
if len(values) > 1 {
return fmt.Errorf("%s must contain exactly one value", ProfilesDevelopmentVersionHeader)
}
version := "1"
if len(values) == 1 {
version = values[0]
}
// An exact match also rejects malformed values, including empty strings,
// leading zeros, and comma-separated values combined by an HTTP intermediary.
if version != ProfilesDevelopmentVersion {
return fmt.Errorf("invalid or unsupported %s: supported version is %s", ProfilesDevelopmentVersionHeader, ProfilesDevelopmentVersion)
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlp // import "go.opentelemetry.io/collector/pdata/internal/otlp"
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// MigrateTraces implements any translation needed due to deprecation in OTLP traces protocol.
// Any ptrace.Unmarshaler implementation from OTLP (proto/json) MUST call this, and the gRPC Server implementation.
func MigrateTraces(rss []*internal.ResourceSpans) {
for _, rs := range rss {
if len(rs.ScopeSpans) == 0 {
rs.ScopeSpans = rs.DeprecatedScopeSpans
}
rs.DeprecatedScopeSpans = nil
}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
import (
"encoding/hex"
"errors"
"go.opentelemetry.io/collector/pdata/internal/json"
)
const profileIDSize = 16
var errUnmarshalProfileID = errors.New("unmarshal: invalid ProfileID length")
// ProfileID is a custom data type that is used for all profile_id fields in OTLP
// Protobuf messages.
type ProfileID [profileIDSize]byte
func DeleteProfileID(*ProfileID, bool) {}
func CopyProfileID(dest, src *ProfileID) {
*dest = *src
}
// IsEmpty returns true if id doesn't contain at least one non-zero byte.
func (pid ProfileID) IsEmpty() bool {
return pid == [profileIDSize]byte{}
}
// SizeProto returns the size of the data to serialize in proto format.
func (pid ProfileID) SizeProto() int {
if pid.IsEmpty() {
return 0
}
return profileIDSize
}
// MarshalProto converts profile ID into a binary representation. Called by Protobuf serialization.
func (pid ProfileID) MarshalProto(buf []byte) int {
if pid.IsEmpty() {
return 0
}
return copy(buf[len(buf)-profileIDSize:], pid[:])
}
// UnmarshalProto inflates this profile ID from binary representation. Called by Protobuf serialization.
func (pid *ProfileID) UnmarshalProto(buf []byte) error {
if len(buf) == 0 {
*pid = [profileIDSize]byte{}
return nil
}
if len(buf) != profileIDSize {
return errUnmarshalProfileID
}
copy(pid[:], buf)
return nil
}
// MarshalJSON converts ProfileID into a hex string.
//
//nolint:govet
func (pid ProfileID) MarshalJSON(dest *json.Stream) {
dest.WriteString(hex.EncodeToString(pid[:]))
}
// UnmarshalJSON decodes ProfileID from hex string.
//
//nolint:govet
func (pid *ProfileID) UnmarshalJSON(iter *json.Iterator) {
*pid = [profileIDSize]byte{}
unmarshalJSON(pid[:], iter)
}
func GenTestProfileID() *ProfileID {
pid := ProfileID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})
return &pid
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package proto // import "go.opentelemetry.io/collector/pdata/internal/proto"
// EncodeVarint encodes the variant at the end of the buffer.
func EncodeVarint(buf []byte, offset int, v uint64) int {
offset -= Sov(v)
base := offset
for v >= 1<<7 {
buf[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
buf[offset] = uint8(v)
return base
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package proto // import "go.opentelemetry.io/collector/pdata/internal/proto"
import (
"math/bits"
)
func Sov(x uint64) (n int) {
return (bits.Len64(x|1) + 6) / 7
}
func Soz(x uint64) (n int) {
return Sov((x << 1) ^ uint64((int64(x) >> 63)))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package proto // import "go.opentelemetry.io/collector/pdata/internal/proto"
import (
"encoding/binary"
"errors"
"fmt"
"io"
)
// WireType represents the proto wire type.
type WireType int8
const (
WireTypeVarint WireType = 0
WireTypeI64 WireType = 1
WireTypeLen WireType = 2
WireTypeStartGroup WireType = 3
WireTypeEndGroup WireType = 4
WireTypeI32 WireType = 5
)
const RecursionLimit = 100
var (
ErrInvalidLength = errors.New("proto: negative length found during unmarshaling")
ErrIntOverflow = errors.New("proto: integer overflow")
ErrRecursionDepth = errors.New("proto: exceeded max recursion depth")
ErrUnexpectedEndOfGroup = errors.New("proto: unexpected end of group")
)
// ConsumeUnknown parses buf starting at pos as a wireType field, reporting the new position.
func ConsumeUnknown(buf []byte, pos int, wireType WireType) (int, error) {
var err error
l := len(buf)
depth := 0
for pos < l {
switch wireType {
case WireTypeVarint:
_, pos, err = ConsumeVarint(buf, pos)
return pos, err
case WireTypeI64:
_, pos, err = ConsumeI64(buf, pos)
return pos, err
case WireTypeLen:
_, pos, err = ConsumeLen(buf, pos)
return pos, err
case WireTypeStartGroup:
depth++
case WireTypeEndGroup:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroup
}
depth--
case WireTypeI32:
_, pos, err = ConsumeI32(buf, pos)
return pos, err
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
// Only when parsing a group can be here, if done return otherwise parse more tags.
if depth == 0 {
return pos, nil
}
// If in a group parsing, move to the next tag.
_, wireType, pos, err = ConsumeTag(buf, pos)
if err != nil {
return 0, err
}
}
return 0, io.ErrUnexpectedEOF
}
// ConsumeI64 parses buf starting at pos as a WireTypeI64 field, reporting the value and the new position.
func ConsumeI64(buf []byte, pos int) (uint64, int, error) {
pos += 8
if pos < 0 || pos > len(buf) {
return 0, 0, io.ErrUnexpectedEOF
}
return binary.LittleEndian.Uint64(buf[pos-8:]), pos, nil
}
// ConsumeLen parses buf starting at pos as a WireTypeLen field, reporting the len and the new position.
func ConsumeLen(buf []byte, pos int) (int, int, error) {
var num uint64
var err error
num, pos, err = ConsumeVarint(buf, pos)
if err != nil {
return 0, 0, err
}
length := int(num)
if length < 0 {
return 0, 0, ErrInvalidLength
}
pos += length
if pos < 0 || pos > len(buf) {
return 0, 0, io.ErrUnexpectedEOF
}
return length, pos, nil
}
// ConsumeI32 parses buf starting at pos as a WireTypeI32 field, reporting the value and the new position.
func ConsumeI32(buf []byte, pos int) (uint32, int, error) {
pos += 4
if pos < 0 || pos > len(buf) {
return 0, 0, io.ErrUnexpectedEOF
}
return binary.LittleEndian.Uint32(buf[pos-4:]), pos, nil
}
// ConsumeTag parses buf starting at pos as a varint-encoded tag, reporting the new position.
func ConsumeTag(buf []byte, pos int) (int32, WireType, int, error) {
tag, pos, err := ConsumeVarint(buf, pos)
if err != nil {
return 0, 0, 0, err
}
fieldNum := int32(tag >> 3)
wireType := int8(tag & 0x7)
if fieldNum <= 0 {
return 0, 0, 0, fmt.Errorf("proto: Link: illegal field=%d (tag=%d, pos=%d)", fieldNum, tag, pos)
}
return fieldNum, WireType(wireType), pos, nil
}
// ConsumeVarint parses buf starting at pos as a varint-encoded uint64, reporting the new position.
func ConsumeVarint(buf []byte, pos int) (uint64, int, error) {
l := len(buf)
var num uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, 0, ErrIntOverflow
}
if pos >= l {
return 0, 0, io.ErrUnexpectedEOF
}
b := buf[pos]
pos++
num |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
return num, pos, nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
import (
"encoding/hex"
"errors"
"go.opentelemetry.io/collector/pdata/internal/json"
)
const spanIDSize = 8
var errUnmarshalSpanID = errors.New("unmarshal: invalid SpanID length")
// SpanID is a custom data type that is used for all span_id fields in OTLP
// Protobuf messages.
type SpanID [spanIDSize]byte
func DeleteSpanID(*SpanID, bool) {}
func CopySpanID(dest, src *SpanID) {
*dest = *src
}
// IsEmpty returns true if id doesn't contain at least one non-zero byte.
func (sid SpanID) IsEmpty() bool {
return sid == [spanIDSize]byte{}
}
// SizeProto returns the size of the data to serialize in proto format.
func (sid SpanID) SizeProto() int {
if sid.IsEmpty() {
return 0
}
return spanIDSize
}
// MarshalProto converts span ID into a binary representation. Called by Protobuf serialization.
func (sid SpanID) MarshalProto(buf []byte) int {
if sid.IsEmpty() {
return 0
}
return copy(buf[len(buf)-spanIDSize:], sid[:])
}
// UnmarshalProto inflates this span ID from binary representation. Called by Protobuf serialization.
func (sid *SpanID) UnmarshalProto(data []byte) error {
if len(data) == 0 {
*sid = [spanIDSize]byte{}
return nil
}
if len(data) != spanIDSize {
return errUnmarshalSpanID
}
copy(sid[:], data)
return nil
}
// MarshalJSON converts SpanID into a hex string.
//
//nolint:govet
func (sid SpanID) MarshalJSON(dest *json.Stream) {
dest.WriteString(hex.EncodeToString(sid[:]))
}
// UnmarshalJSON decodes SpanID from hex string.
//
//nolint:govet
func (sid *SpanID) UnmarshalJSON(iter *json.Iterator) {
*sid = [spanIDSize]byte{}
unmarshalJSON(sid[:], iter)
}
func GenTestSpanID() *SpanID {
sid := SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1})
return &sid
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
import (
"sync/atomic"
)
// State defines an ownership state of pmetric.Metrics, plog.Logs, ptrace.Traces or pprofile.Profiles.
type State struct {
refs atomic.Int32
state uint32
}
const (
defaultState uint32 = 0
stateReadOnlyBit = uint32(1 << 0)
statePipelineOwnedBit = uint32(1 << 1)
)
func NewState() *State {
st := &State{
state: defaultState,
}
st.refs.Store(1)
return st
}
func (st *State) MarkReadOnly() {
st.state |= stateReadOnlyBit
}
func (st *State) IsReadOnly() bool {
return st.state&stateReadOnlyBit != 0
}
// AssertMutable panics if the state is not StateMutable.
func (st *State) AssertMutable() {
if st.state&stateReadOnlyBit != 0 {
panic("invalid access to shared data")
}
}
// MarkPipelineOwned marks the data as owned by the pipeline, returns true if the data were
// previously not owned by the pipeline, otherwise false.
func (st *State) MarkPipelineOwned() bool {
if st.state&statePipelineOwnedBit != 0 {
return false
}
st.state |= statePipelineOwnedBit
return true
}
// Ref add one to the count of active references.
func (st *State) Ref() {
st.refs.Add(1)
}
// Unref returns true if reference count got to 0 which means no more active references,
// otherwise it returns false.
func (st *State) Unref() bool {
refs := st.refs.Add(-1)
switch {
case refs > 0:
return false
case refs == 0:
return true
default:
panic("Cannot unref freed data")
}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
import (
"encoding/hex"
"errors"
"go.opentelemetry.io/collector/pdata/internal/json"
)
const traceIDSize = 16
var errUnmarshalTraceID = errors.New("unmarshal: invalid TraceID length")
// TraceID is a custom data type that is used for all trace_id fields in OTLP
// Protobuf messages.
type TraceID [traceIDSize]byte
func DeleteTraceID(*TraceID, bool) {}
func CopyTraceID(dest, src *TraceID) {
*dest = *src
}
// IsEmpty returns true if id doesn't contain at least one non-zero byte.
func (tid TraceID) IsEmpty() bool {
return tid == [traceIDSize]byte{}
}
// SizeProto returns the size of the data to serialize in proto format.
func (tid TraceID) SizeProto() int {
if tid.IsEmpty() {
return 0
}
return traceIDSize
}
// MarshalProto converts trace ID into a binary representation. Called by Protobuf serialization.
func (tid TraceID) MarshalProto(buf []byte) int {
if tid.IsEmpty() {
return 0
}
return copy(buf[len(buf)-traceIDSize:], tid[:])
}
// UnmarshalProto inflates this trace ID from binary representation. Called by Protobuf serialization.
func (tid *TraceID) UnmarshalProto(buf []byte) error {
if len(buf) == 0 {
*tid = [traceIDSize]byte{}
return nil
}
if len(buf) != traceIDSize {
return errUnmarshalTraceID
}
copy(tid[:], buf)
return nil
}
// MarshalJSON converts TraceID into a hex string.
//
//nolint:govet
func (tid TraceID) MarshalJSON(dest *json.Stream) {
dest.WriteString(hex.EncodeToString(tid[:]))
}
// UnmarshalJSON decodes TraceID from hex string.
//
//nolint:govet
func (tid *TraceID) UnmarshalJSON(iter *json.Iterator) {
*tid = [profileIDSize]byte{}
unmarshalJSON(tid[:], iter)
}
func GenTestTraceID() *TraceID {
tid := TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})
return &tid
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
// LogsToProto internal helper to convert Logs to protobuf representation.
func LogsToProto(l LogsWrapper) LogsData {
return LogsData{
ResourceLogs: l.orig.ResourceLogs,
}
}
// LogsFromProto internal helper to convert protobuf representation to Logs.
// This function set exclusive state assuming that it's called only once per Logs.
func LogsFromProto(orig LogsData) LogsWrapper {
return NewLogsWrapper(&ExportLogsServiceRequest{
ResourceLogs: orig.ResourceLogs,
}, NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
type MapWrapper struct {
orig *[]KeyValue
state *State
}
func GetMapOrig(ms MapWrapper) *[]KeyValue {
return ms.orig
}
func GetMapState(ms MapWrapper) *State {
return ms.state
}
func NewMapWrapper(orig *[]KeyValue, state *State) MapWrapper {
return MapWrapper{orig: orig, state: state}
}
func GenTestMapWrapper() MapWrapper {
orig := GenTestKeyValueSlice()
return NewMapWrapper(&orig, NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
// MetricsToProto internal helper to convert Metrics to protobuf representation.
func MetricsToProto(l MetricsWrapper) MetricsData {
return MetricsData{
ResourceMetrics: l.orig.ResourceMetrics,
}
}
// MetricsFromProto internal helper to convert protobuf representation to Metrics.
// This function set exclusive state assuming that it's called only once per Metrics.
func MetricsFromProto(orig MetricsData) MetricsWrapper {
return NewMetricsWrapper(&ExportMetricsServiceRequest{
ResourceMetrics: orig.ResourceMetrics,
}, NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
// ProfilesToProto internal helper to convert Profiles to protobuf representation.
func ProfilesToProto(l ProfilesWrapper) ProfilesData {
return ProfilesData{
ResourceProfiles: l.orig.ResourceProfiles,
Dictionary: l.orig.Dictionary,
}
}
// ProfilesFromProto internal helper to convert protobuf representation to Profiles.
// This function set exclusive state assuming that it's called only once per Profiles.
func ProfilesFromProto(orig ProfilesData) ProfilesWrapper {
return NewProfilesWrapper(&ExportProfilesServiceRequest{
ResourceProfiles: orig.ResourceProfiles,
Dictionary: orig.Dictionary,
}, NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
// TracesToProto internal helper to convert Traces to protobuf representation.
func TracesToProto(l TracesWrapper) TracesData {
return TracesData{
ResourceSpans: l.orig.ResourceSpans,
}
}
// TracesFromProto internal helper to convert protobuf representation to Traces.
// This function set exclusive state assuming that it's called only once per Traces.
func TracesFromProto(orig TracesData) TracesWrapper {
return NewTracesWrapper(&ExportTraceServiceRequest{
ResourceSpans: orig.ResourceSpans,
}, NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
type TraceStateWrapper struct {
orig *string
state *State
}
func GetTraceStateOrig(ms TraceStateWrapper) *string {
return ms.orig
}
func GetTraceStateState(ms TraceStateWrapper) *State {
return ms.state
}
func NewTraceStateWrapper(orig *string, state *State) TraceStateWrapper {
return TraceStateWrapper{orig: orig, state: state}
}
func GenTestTraceStateWrapper() TraceStateWrapper {
return NewTraceStateWrapper(GenTestTraceState(), NewState())
}
func GenTestTraceState() *string {
orig := new(string)
*orig = "rojo=00f067aa0ba902b7"
return orig
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package internal // import "go.opentelemetry.io/collector/pdata/internal"
type ValueWrapper struct {
orig *AnyValue
state *State
}
func GetValueOrig(ms ValueWrapper) *AnyValue {
return ms.orig
}
func GetValueState(ms ValueWrapper) *State {
return ms.state
}
func NewValueWrapper(orig *AnyValue, state *State) ValueWrapper {
return ValueWrapper{orig: orig, state: state}
}
func GenTestValueWrapper() ValueWrapper {
orig := GenTestAnyValue()
return NewValueWrapper(orig, NewState())
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pcommon
import (
"iter"
"slices"
"go.opentelemetry.io/collector/pdata/internal"
)
// ByteSlice represents a []byte slice.
// The instance of ByteSlice can be assigned to multiple objects since it's immutable.
//
// Must use NewByteSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ByteSlice internal.ByteSliceWrapper
func (ms ByteSlice) getOrig() *[]byte {
return internal.GetByteSliceOrig(internal.ByteSliceWrapper(ms))
}
func (ms ByteSlice) getState() *internal.State {
return internal.GetByteSliceState(internal.ByteSliceWrapper(ms))
}
// NewByteSlice creates a new empty ByteSlice.
func NewByteSlice() ByteSlice {
orig := []byte(nil)
return ByteSlice(internal.NewByteSliceWrapper(&orig, internal.NewState()))
}
// AsRaw returns a copy of the []byte slice.
func (ms ByteSlice) AsRaw() []byte {
return copyByteSlice(nil, *ms.getOrig())
}
// FromRaw copies raw []byte into the slice ByteSlice.
func (ms ByteSlice) FromRaw(val []byte) {
ms.getState().AssertMutable()
*ms.getOrig() = copyByteSlice(*ms.getOrig(), val)
}
// Len returns length of the []byte slice value.
// Equivalent of len(byteSlice).
func (ms ByteSlice) Len() int {
return len(*ms.getOrig())
}
// At returns an item from particular index.
// Equivalent of byteSlice[i].
func (ms ByteSlice) At(i int) byte {
return (*ms.getOrig())[i]
}
// All returns an iterator over index-value pairs in the slice.
func (ms ByteSlice) All() iter.Seq2[int, byte] {
return func(yield func(int, byte) bool) {
for i := 0; i < ms.Len(); i++ {
if !yield(i, ms.At(i)) {
return
}
}
}
}
// SetAt sets byte item at particular index.
// Equivalent of byteSlice[i] = val
func (ms ByteSlice) SetAt(i int, val byte) {
ms.getState().AssertMutable()
(*ms.getOrig())[i] = val
}
// EnsureCapacity ensures ByteSlice has at least the specified capacity.
// 1. If the newCap <= cap, then is no change in capacity.
// 2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:
// buf := make([]byte, len(byteSlice), newCap)
// copy(buf, byteSlice)
// byteSlice = buf
func (ms ByteSlice) EnsureCapacity(newCap int) {
ms.getState().AssertMutable()
oldCap := cap(*ms.getOrig())
if newCap <= oldCap {
return
}
newOrig := make([]byte, len(*ms.getOrig()), newCap)
copy(newOrig, *ms.getOrig())
*ms.getOrig() = newOrig
}
// Append appends extra elements to ByteSlice.
// Equivalent of byteSlice = append(byteSlice, elms...)
func (ms ByteSlice) Append(elms ...byte) {
ms.getState().AssertMutable()
*ms.getOrig() = append(*ms.getOrig(), elms...)
}
// MoveTo moves all elements from the current slice overriding the destination and
// resetting the current instance to its zero value.
func (ms ByteSlice) MoveTo(dest ByteSlice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = *ms.getOrig()
*ms.getOrig() = nil
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (ms ByteSlice) MoveAndAppendTo(dest ByteSlice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
if *dest.getOrig() == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.getOrig() = *ms.getOrig()
} else {
*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)
}
*ms.getOrig() = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (ms ByteSlice) RemoveIf(f func(byte) bool) {
ms.getState().AssertMutable()
newLen := 0
for i := 0; i < len(*ms.getOrig()); i++ {
if f((*ms.getOrig())[i]) {
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*ms.getOrig())[newLen] = (*ms.getOrig())[i]
var zero byte
(*ms.getOrig())[i] = zero
newLen++
}
*ms.getOrig() = (*ms.getOrig())[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (ms ByteSlice) CopyTo(dest ByteSlice) {
dest.getState().AssertMutable()
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = copyByteSlice(*dest.getOrig(), *ms.getOrig())
}
// Equal checks equality with another ByteSlice
func (ms ByteSlice) Equal(val ByteSlice) bool {
return slices.Equal(*ms.getOrig(), *val.getOrig())
}
func copyByteSlice(dst, src []byte) []byte {
return append(dst[:0], src...)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pcommon
import (
"iter"
"slices"
"go.opentelemetry.io/collector/pdata/internal"
)
// Float64Slice represents a []float64 slice.
// The instance of Float64Slice can be assigned to multiple objects since it's immutable.
//
// Must use NewFloat64Slice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Float64Slice internal.Float64SliceWrapper
func (ms Float64Slice) getOrig() *[]float64 {
return internal.GetFloat64SliceOrig(internal.Float64SliceWrapper(ms))
}
func (ms Float64Slice) getState() *internal.State {
return internal.GetFloat64SliceState(internal.Float64SliceWrapper(ms))
}
// NewFloat64Slice creates a new empty Float64Slice.
func NewFloat64Slice() Float64Slice {
orig := []float64(nil)
return Float64Slice(internal.NewFloat64SliceWrapper(&orig, internal.NewState()))
}
// AsRaw returns a copy of the []float64 slice.
func (ms Float64Slice) AsRaw() []float64 {
return copyFloat64Slice(nil, *ms.getOrig())
}
// FromRaw copies raw []float64 into the slice Float64Slice.
func (ms Float64Slice) FromRaw(val []float64) {
ms.getState().AssertMutable()
*ms.getOrig() = copyFloat64Slice(*ms.getOrig(), val)
}
// Len returns length of the []float64 slice value.
// Equivalent of len(float64Slice).
func (ms Float64Slice) Len() int {
return len(*ms.getOrig())
}
// At returns an item from particular index.
// Equivalent of float64Slice[i].
func (ms Float64Slice) At(i int) float64 {
return (*ms.getOrig())[i]
}
// All returns an iterator over index-value pairs in the slice.
func (ms Float64Slice) All() iter.Seq2[int, float64] {
return func(yield func(int, float64) bool) {
for i := 0; i < ms.Len(); i++ {
if !yield(i, ms.At(i)) {
return
}
}
}
}
// SetAt sets float64 item at particular index.
// Equivalent of float64Slice[i] = val
func (ms Float64Slice) SetAt(i int, val float64) {
ms.getState().AssertMutable()
(*ms.getOrig())[i] = val
}
// EnsureCapacity ensures Float64Slice has at least the specified capacity.
// 1. If the newCap <= cap, then is no change in capacity.
// 2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:
// buf := make([]float64, len(float64Slice), newCap)
// copy(buf, float64Slice)
// float64Slice = buf
func (ms Float64Slice) EnsureCapacity(newCap int) {
ms.getState().AssertMutable()
oldCap := cap(*ms.getOrig())
if newCap <= oldCap {
return
}
newOrig := make([]float64, len(*ms.getOrig()), newCap)
copy(newOrig, *ms.getOrig())
*ms.getOrig() = newOrig
}
// Append appends extra elements to Float64Slice.
// Equivalent of float64Slice = append(float64Slice, elms...)
func (ms Float64Slice) Append(elms ...float64) {
ms.getState().AssertMutable()
*ms.getOrig() = append(*ms.getOrig(), elms...)
}
// MoveTo moves all elements from the current slice overriding the destination and
// resetting the current instance to its zero value.
func (ms Float64Slice) MoveTo(dest Float64Slice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = *ms.getOrig()
*ms.getOrig() = nil
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (ms Float64Slice) MoveAndAppendTo(dest Float64Slice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
if *dest.getOrig() == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.getOrig() = *ms.getOrig()
} else {
*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)
}
*ms.getOrig() = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (ms Float64Slice) RemoveIf(f func(float64) bool) {
ms.getState().AssertMutable()
newLen := 0
for i := 0; i < len(*ms.getOrig()); i++ {
if f((*ms.getOrig())[i]) {
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*ms.getOrig())[newLen] = (*ms.getOrig())[i]
var zero float64
(*ms.getOrig())[i] = zero
newLen++
}
*ms.getOrig() = (*ms.getOrig())[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (ms Float64Slice) CopyTo(dest Float64Slice) {
dest.getState().AssertMutable()
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = copyFloat64Slice(*dest.getOrig(), *ms.getOrig())
}
// Equal checks equality with another Float64Slice
func (ms Float64Slice) Equal(val Float64Slice) bool {
return slices.Equal(*ms.getOrig(), *val.getOrig())
}
func copyFloat64Slice(dst, src []float64) []float64 {
return append(dst[:0], src...)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pcommon
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// InstrumentationScope is a message representing the instrumentation scope information.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewInstrumentationScope function to create new instances.
// Important: zero-initialized instance is not valid for use.
type InstrumentationScope internal.InstrumentationScopeWrapper
func newInstrumentationScope(orig *internal.InstrumentationScope, state *internal.State) InstrumentationScope {
return InstrumentationScope(internal.NewInstrumentationScopeWrapper(orig, state))
}
// NewInstrumentationScope creates a new empty InstrumentationScope.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewInstrumentationScope() InstrumentationScope {
return newInstrumentationScope(internal.NewInstrumentationScope(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms InstrumentationScope) MoveTo(dest InstrumentationScope) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
internal.DeleteInstrumentationScope(dest.getOrig(), false)
*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()
}
// Name returns the name associated with this InstrumentationScope.
func (ms InstrumentationScope) Name() string {
return ms.getOrig().Name
}
// SetName replaces the name associated with this InstrumentationScope.
func (ms InstrumentationScope) SetName(v string) {
ms.getState().AssertMutable()
ms.getOrig().Name = v
}
// Version returns the version associated with this InstrumentationScope.
func (ms InstrumentationScope) Version() string {
return ms.getOrig().Version
}
// SetVersion replaces the version associated with this InstrumentationScope.
func (ms InstrumentationScope) SetVersion(v string) {
ms.getState().AssertMutable()
ms.getOrig().Version = v
}
// Attributes returns the Attributes associated with this InstrumentationScope.
func (ms InstrumentationScope) Attributes() Map {
return Map(internal.NewMapWrapper(&ms.getOrig().Attributes, ms.getState()))
}
// DroppedAttributesCount returns the droppedattributescount associated with this InstrumentationScope.
func (ms InstrumentationScope) DroppedAttributesCount() uint32 {
return ms.getOrig().DroppedAttributesCount
}
// SetDroppedAttributesCount replaces the droppedattributescount associated with this InstrumentationScope.
func (ms InstrumentationScope) SetDroppedAttributesCount(v uint32) {
ms.getState().AssertMutable()
ms.getOrig().DroppedAttributesCount = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms InstrumentationScope) CopyTo(dest InstrumentationScope) {
dest.getState().AssertMutable()
internal.CopyInstrumentationScope(dest.getOrig(), ms.getOrig())
}
func (ms InstrumentationScope) getOrig() *internal.InstrumentationScope {
return internal.GetInstrumentationScopeOrig(internal.InstrumentationScopeWrapper(ms))
}
func (ms InstrumentationScope) getState() *internal.State {
return internal.GetInstrumentationScopeState(internal.InstrumentationScopeWrapper(ms))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pcommon
import (
"iter"
"slices"
"go.opentelemetry.io/collector/pdata/internal"
)
// Int32Slice represents a []int32 slice.
// The instance of Int32Slice can be assigned to multiple objects since it's immutable.
//
// Must use NewInt32Slice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Int32Slice internal.Int32SliceWrapper
func (ms Int32Slice) getOrig() *[]int32 {
return internal.GetInt32SliceOrig(internal.Int32SliceWrapper(ms))
}
func (ms Int32Slice) getState() *internal.State {
return internal.GetInt32SliceState(internal.Int32SliceWrapper(ms))
}
// NewInt32Slice creates a new empty Int32Slice.
func NewInt32Slice() Int32Slice {
orig := []int32(nil)
return Int32Slice(internal.NewInt32SliceWrapper(&orig, internal.NewState()))
}
// AsRaw returns a copy of the []int32 slice.
func (ms Int32Slice) AsRaw() []int32 {
return copyInt32Slice(nil, *ms.getOrig())
}
// FromRaw copies raw []int32 into the slice Int32Slice.
func (ms Int32Slice) FromRaw(val []int32) {
ms.getState().AssertMutable()
*ms.getOrig() = copyInt32Slice(*ms.getOrig(), val)
}
// Len returns length of the []int32 slice value.
// Equivalent of len(int32Slice).
func (ms Int32Slice) Len() int {
return len(*ms.getOrig())
}
// At returns an item from particular index.
// Equivalent of int32Slice[i].
func (ms Int32Slice) At(i int) int32 {
return (*ms.getOrig())[i]
}
// All returns an iterator over index-value pairs in the slice.
func (ms Int32Slice) All() iter.Seq2[int, int32] {
return func(yield func(int, int32) bool) {
for i := 0; i < ms.Len(); i++ {
if !yield(i, ms.At(i)) {
return
}
}
}
}
// SetAt sets int32 item at particular index.
// Equivalent of int32Slice[i] = val
func (ms Int32Slice) SetAt(i int, val int32) {
ms.getState().AssertMutable()
(*ms.getOrig())[i] = val
}
// EnsureCapacity ensures Int32Slice has at least the specified capacity.
// 1. If the newCap <= cap, then is no change in capacity.
// 2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:
// buf := make([]int32, len(int32Slice), newCap)
// copy(buf, int32Slice)
// int32Slice = buf
func (ms Int32Slice) EnsureCapacity(newCap int) {
ms.getState().AssertMutable()
oldCap := cap(*ms.getOrig())
if newCap <= oldCap {
return
}
newOrig := make([]int32, len(*ms.getOrig()), newCap)
copy(newOrig, *ms.getOrig())
*ms.getOrig() = newOrig
}
// Append appends extra elements to Int32Slice.
// Equivalent of int32Slice = append(int32Slice, elms...)
func (ms Int32Slice) Append(elms ...int32) {
ms.getState().AssertMutable()
*ms.getOrig() = append(*ms.getOrig(), elms...)
}
// MoveTo moves all elements from the current slice overriding the destination and
// resetting the current instance to its zero value.
func (ms Int32Slice) MoveTo(dest Int32Slice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = *ms.getOrig()
*ms.getOrig() = nil
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (ms Int32Slice) MoveAndAppendTo(dest Int32Slice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
if *dest.getOrig() == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.getOrig() = *ms.getOrig()
} else {
*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)
}
*ms.getOrig() = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (ms Int32Slice) RemoveIf(f func(int32) bool) {
ms.getState().AssertMutable()
newLen := 0
for i := 0; i < len(*ms.getOrig()); i++ {
if f((*ms.getOrig())[i]) {
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*ms.getOrig())[newLen] = (*ms.getOrig())[i]
var zero int32
(*ms.getOrig())[i] = zero
newLen++
}
*ms.getOrig() = (*ms.getOrig())[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (ms Int32Slice) CopyTo(dest Int32Slice) {
dest.getState().AssertMutable()
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = copyInt32Slice(*dest.getOrig(), *ms.getOrig())
}
// Equal checks equality with another Int32Slice
func (ms Int32Slice) Equal(val Int32Slice) bool {
return slices.Equal(*ms.getOrig(), *val.getOrig())
}
func copyInt32Slice(dst, src []int32) []int32 {
return append(dst[:0], src...)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pcommon
import (
"iter"
"slices"
"go.opentelemetry.io/collector/pdata/internal"
)
// Int64Slice represents a []int64 slice.
// The instance of Int64Slice can be assigned to multiple objects since it's immutable.
//
// Must use NewInt64Slice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Int64Slice internal.Int64SliceWrapper
func (ms Int64Slice) getOrig() *[]int64 {
return internal.GetInt64SliceOrig(internal.Int64SliceWrapper(ms))
}
func (ms Int64Slice) getState() *internal.State {
return internal.GetInt64SliceState(internal.Int64SliceWrapper(ms))
}
// NewInt64Slice creates a new empty Int64Slice.
func NewInt64Slice() Int64Slice {
orig := []int64(nil)
return Int64Slice(internal.NewInt64SliceWrapper(&orig, internal.NewState()))
}
// AsRaw returns a copy of the []int64 slice.
func (ms Int64Slice) AsRaw() []int64 {
return copyInt64Slice(nil, *ms.getOrig())
}
// FromRaw copies raw []int64 into the slice Int64Slice.
func (ms Int64Slice) FromRaw(val []int64) {
ms.getState().AssertMutable()
*ms.getOrig() = copyInt64Slice(*ms.getOrig(), val)
}
// Len returns length of the []int64 slice value.
// Equivalent of len(int64Slice).
func (ms Int64Slice) Len() int {
return len(*ms.getOrig())
}
// At returns an item from particular index.
// Equivalent of int64Slice[i].
func (ms Int64Slice) At(i int) int64 {
return (*ms.getOrig())[i]
}
// All returns an iterator over index-value pairs in the slice.
func (ms Int64Slice) All() iter.Seq2[int, int64] {
return func(yield func(int, int64) bool) {
for i := 0; i < ms.Len(); i++ {
if !yield(i, ms.At(i)) {
return
}
}
}
}
// SetAt sets int64 item at particular index.
// Equivalent of int64Slice[i] = val
func (ms Int64Slice) SetAt(i int, val int64) {
ms.getState().AssertMutable()
(*ms.getOrig())[i] = val
}
// EnsureCapacity ensures Int64Slice has at least the specified capacity.
// 1. If the newCap <= cap, then is no change in capacity.
// 2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:
// buf := make([]int64, len(int64Slice), newCap)
// copy(buf, int64Slice)
// int64Slice = buf
func (ms Int64Slice) EnsureCapacity(newCap int) {
ms.getState().AssertMutable()
oldCap := cap(*ms.getOrig())
if newCap <= oldCap {
return
}
newOrig := make([]int64, len(*ms.getOrig()), newCap)
copy(newOrig, *ms.getOrig())
*ms.getOrig() = newOrig
}
// Append appends extra elements to Int64Slice.
// Equivalent of int64Slice = append(int64Slice, elms...)
func (ms Int64Slice) Append(elms ...int64) {
ms.getState().AssertMutable()
*ms.getOrig() = append(*ms.getOrig(), elms...)
}
// MoveTo moves all elements from the current slice overriding the destination and
// resetting the current instance to its zero value.
func (ms Int64Slice) MoveTo(dest Int64Slice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = *ms.getOrig()
*ms.getOrig() = nil
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (ms Int64Slice) MoveAndAppendTo(dest Int64Slice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
if *dest.getOrig() == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.getOrig() = *ms.getOrig()
} else {
*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)
}
*ms.getOrig() = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (ms Int64Slice) RemoveIf(f func(int64) bool) {
ms.getState().AssertMutable()
newLen := 0
for i := 0; i < len(*ms.getOrig()); i++ {
if f((*ms.getOrig())[i]) {
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*ms.getOrig())[newLen] = (*ms.getOrig())[i]
var zero int64
(*ms.getOrig())[i] = zero
newLen++
}
*ms.getOrig() = (*ms.getOrig())[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (ms Int64Slice) CopyTo(dest Int64Slice) {
dest.getState().AssertMutable()
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = copyInt64Slice(*dest.getOrig(), *ms.getOrig())
}
// Equal checks equality with another Int64Slice
func (ms Int64Slice) Equal(val Int64Slice) bool {
return slices.Equal(*ms.getOrig(), *val.getOrig())
}
func copyInt64Slice(dst, src []int64) []int64 {
return append(dst[:0], src...)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pcommon
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Resource is a message representing the resource information.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewResource function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Resource internal.ResourceWrapper
func newResource(orig *internal.Resource, state *internal.State) Resource {
return Resource(internal.NewResourceWrapper(orig, state))
}
// NewResource creates a new empty Resource.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewResource() Resource {
return newResource(internal.NewResource(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Resource) MoveTo(dest Resource) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
internal.DeleteResource(dest.getOrig(), false)
*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()
}
// Attributes returns the Attributes associated with this Resource.
func (ms Resource) Attributes() Map {
return Map(internal.NewMapWrapper(&ms.getOrig().Attributes, ms.getState()))
}
// DroppedAttributesCount returns the droppedattributescount associated with this Resource.
func (ms Resource) DroppedAttributesCount() uint32 {
return ms.getOrig().DroppedAttributesCount
}
// SetDroppedAttributesCount replaces the droppedattributescount associated with this Resource.
func (ms Resource) SetDroppedAttributesCount(v uint32) {
ms.getState().AssertMutable()
ms.getOrig().DroppedAttributesCount = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Resource) CopyTo(dest Resource) {
dest.getState().AssertMutable()
internal.CopyResource(dest.getOrig(), ms.getOrig())
}
func (ms Resource) getOrig() *internal.Resource {
return internal.GetResourceOrig(internal.ResourceWrapper(ms))
}
func (ms Resource) getState() *internal.State {
return internal.GetResourceState(internal.ResourceWrapper(ms))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pcommon
import (
"iter"
"go.opentelemetry.io/collector/pdata/internal"
)
// Slice logically represents a slice of Value.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Slice internal.SliceWrapper
func newSlice(orig *[]internal.AnyValue, state *internal.State) Slice {
return Slice(internal.NewSliceWrapper(orig, state))
}
// NewSlice creates a SliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewSlice() Slice {
orig := []internal.AnyValue(nil)
return newSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewSlice()".
func (es Slice) Len() int {
return len(*es.getOrig())
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es Slice) At(i int) Value {
return newValue(&(*es.getOrig())[i], es.getState())
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es Slice) All() iter.Seq2[int, Value] {
return func(yield func(int, Value) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new Slice can be initialized:
//
// es := NewSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es Slice) EnsureCapacity(newCap int) {
es.getState().AssertMutable()
oldCap := cap(*es.getOrig())
if newCap <= oldCap {
return
}
newOrig := make([]internal.AnyValue, len(*es.getOrig()), newCap)
copy(newOrig, *es.getOrig())
*es.getOrig() = newOrig
}
// AppendEmpty will append to the end of the slice an empty Value.
// It returns the newly added Value.
func (es Slice) AppendEmpty() Value {
es.getState().AssertMutable()
*es.getOrig() = append(*es.getOrig(), internal.AnyValue{})
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es Slice) MoveAndAppendTo(dest Slice) {
es.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.getOrig() == dest.getOrig() {
return
}
if *dest.getOrig() == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.getOrig() = *es.getOrig()
} else {
*dest.getOrig() = append(*dest.getOrig(), *es.getOrig()...)
}
*es.getOrig() = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es Slice) RemoveIf(f func(Value) bool) {
es.getState().AssertMutable()
newLen := 0
for i := 0; i < len(*es.getOrig()); i++ {
if f(es.At(i)) {
internal.DeleteAnyValue(&(*es.getOrig())[i], false)
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.getOrig())[newLen] = (*es.getOrig())[i]
(*es.getOrig())[i].Reset()
newLen++
}
*es.getOrig() = (*es.getOrig())[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es Slice) CopyTo(dest Slice) {
dest.getState().AssertMutable()
if es.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = internal.CopyAnyValueSlice(*dest.getOrig(), *es.getOrig())
}
func (ms Slice) getOrig() *[]internal.AnyValue {
return internal.GetSliceOrig(internal.SliceWrapper(ms))
}
func (ms Slice) getState() *internal.State {
return internal.GetSliceState(internal.SliceWrapper(ms))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pcommon
import (
"iter"
"slices"
"go.opentelemetry.io/collector/pdata/internal"
)
// StringSlice represents a []string slice.
// The instance of StringSlice can be assigned to multiple objects since it's immutable.
//
// Must use NewStringSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type StringSlice internal.StringSliceWrapper
func (ms StringSlice) getOrig() *[]string {
return internal.GetStringSliceOrig(internal.StringSliceWrapper(ms))
}
func (ms StringSlice) getState() *internal.State {
return internal.GetStringSliceState(internal.StringSliceWrapper(ms))
}
// NewStringSlice creates a new empty StringSlice.
func NewStringSlice() StringSlice {
orig := []string(nil)
return StringSlice(internal.NewStringSliceWrapper(&orig, internal.NewState()))
}
// AsRaw returns a copy of the []string slice.
func (ms StringSlice) AsRaw() []string {
return copyStringSlice(nil, *ms.getOrig())
}
// FromRaw copies raw []string into the slice StringSlice.
func (ms StringSlice) FromRaw(val []string) {
ms.getState().AssertMutable()
*ms.getOrig() = copyStringSlice(*ms.getOrig(), val)
}
// Len returns length of the []string slice value.
// Equivalent of len(stringSlice).
func (ms StringSlice) Len() int {
return len(*ms.getOrig())
}
// At returns an item from particular index.
// Equivalent of stringSlice[i].
func (ms StringSlice) At(i int) string {
return (*ms.getOrig())[i]
}
// All returns an iterator over index-value pairs in the slice.
func (ms StringSlice) All() iter.Seq2[int, string] {
return func(yield func(int, string) bool) {
for i := 0; i < ms.Len(); i++ {
if !yield(i, ms.At(i)) {
return
}
}
}
}
// SetAt sets string item at particular index.
// Equivalent of stringSlice[i] = val
func (ms StringSlice) SetAt(i int, val string) {
ms.getState().AssertMutable()
(*ms.getOrig())[i] = val
}
// EnsureCapacity ensures StringSlice has at least the specified capacity.
// 1. If the newCap <= cap, then is no change in capacity.
// 2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:
// buf := make([]string, len(stringSlice), newCap)
// copy(buf, stringSlice)
// stringSlice = buf
func (ms StringSlice) EnsureCapacity(newCap int) {
ms.getState().AssertMutable()
oldCap := cap(*ms.getOrig())
if newCap <= oldCap {
return
}
newOrig := make([]string, len(*ms.getOrig()), newCap)
copy(newOrig, *ms.getOrig())
*ms.getOrig() = newOrig
}
// Append appends extra elements to StringSlice.
// Equivalent of stringSlice = append(stringSlice, elms...)
func (ms StringSlice) Append(elms ...string) {
ms.getState().AssertMutable()
*ms.getOrig() = append(*ms.getOrig(), elms...)
}
// MoveTo moves all elements from the current slice overriding the destination and
// resetting the current instance to its zero value.
func (ms StringSlice) MoveTo(dest StringSlice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = *ms.getOrig()
*ms.getOrig() = nil
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (ms StringSlice) MoveAndAppendTo(dest StringSlice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
if *dest.getOrig() == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.getOrig() = *ms.getOrig()
} else {
*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)
}
*ms.getOrig() = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (ms StringSlice) RemoveIf(f func(string) bool) {
ms.getState().AssertMutable()
newLen := 0
for i := 0; i < len(*ms.getOrig()); i++ {
if f((*ms.getOrig())[i]) {
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*ms.getOrig())[newLen] = (*ms.getOrig())[i]
var zero string
(*ms.getOrig())[i] = zero
newLen++
}
*ms.getOrig() = (*ms.getOrig())[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (ms StringSlice) CopyTo(dest StringSlice) {
dest.getState().AssertMutable()
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = copyStringSlice(*dest.getOrig(), *ms.getOrig())
}
// Equal checks equality with another StringSlice
func (ms StringSlice) Equal(val StringSlice) bool {
return slices.Equal(*ms.getOrig(), *val.getOrig())
}
func copyStringSlice(dst, src []string) []string {
return append(dst[:0], src...)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pcommon
import (
"iter"
"slices"
"go.opentelemetry.io/collector/pdata/internal"
)
// UInt64Slice represents a []uint64 slice.
// The instance of UInt64Slice can be assigned to multiple objects since it's immutable.
//
// Must use NewUInt64Slice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type UInt64Slice internal.UInt64SliceWrapper
func (ms UInt64Slice) getOrig() *[]uint64 {
return internal.GetUInt64SliceOrig(internal.UInt64SliceWrapper(ms))
}
func (ms UInt64Slice) getState() *internal.State {
return internal.GetUInt64SliceState(internal.UInt64SliceWrapper(ms))
}
// NewUInt64Slice creates a new empty UInt64Slice.
func NewUInt64Slice() UInt64Slice {
orig := []uint64(nil)
return UInt64Slice(internal.NewUInt64SliceWrapper(&orig, internal.NewState()))
}
// AsRaw returns a copy of the []uint64 slice.
func (ms UInt64Slice) AsRaw() []uint64 {
return copyUint64Slice(nil, *ms.getOrig())
}
// FromRaw copies raw []uint64 into the slice UInt64Slice.
func (ms UInt64Slice) FromRaw(val []uint64) {
ms.getState().AssertMutable()
*ms.getOrig() = copyUint64Slice(*ms.getOrig(), val)
}
// Len returns length of the []uint64 slice value.
// Equivalent of len(uInt64Slice).
func (ms UInt64Slice) Len() int {
return len(*ms.getOrig())
}
// At returns an item from particular index.
// Equivalent of uInt64Slice[i].
func (ms UInt64Slice) At(i int) uint64 {
return (*ms.getOrig())[i]
}
// All returns an iterator over index-value pairs in the slice.
func (ms UInt64Slice) All() iter.Seq2[int, uint64] {
return func(yield func(int, uint64) bool) {
for i := 0; i < ms.Len(); i++ {
if !yield(i, ms.At(i)) {
return
}
}
}
}
// SetAt sets uint64 item at particular index.
// Equivalent of uInt64Slice[i] = val
func (ms UInt64Slice) SetAt(i int, val uint64) {
ms.getState().AssertMutable()
(*ms.getOrig())[i] = val
}
// EnsureCapacity ensures UInt64Slice has at least the specified capacity.
// 1. If the newCap <= cap, then is no change in capacity.
// 2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:
// buf := make([]uint64, len(uInt64Slice), newCap)
// copy(buf, uInt64Slice)
// uInt64Slice = buf
func (ms UInt64Slice) EnsureCapacity(newCap int) {
ms.getState().AssertMutable()
oldCap := cap(*ms.getOrig())
if newCap <= oldCap {
return
}
newOrig := make([]uint64, len(*ms.getOrig()), newCap)
copy(newOrig, *ms.getOrig())
*ms.getOrig() = newOrig
}
// Append appends extra elements to UInt64Slice.
// Equivalent of uInt64Slice = append(uInt64Slice, elms...)
func (ms UInt64Slice) Append(elms ...uint64) {
ms.getState().AssertMutable()
*ms.getOrig() = append(*ms.getOrig(), elms...)
}
// MoveTo moves all elements from the current slice overriding the destination and
// resetting the current instance to its zero value.
func (ms UInt64Slice) MoveTo(dest UInt64Slice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = *ms.getOrig()
*ms.getOrig() = nil
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (ms UInt64Slice) MoveAndAppendTo(dest UInt64Slice) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
if *dest.getOrig() == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.getOrig() = *ms.getOrig()
} else {
*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)
}
*ms.getOrig() = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (ms UInt64Slice) RemoveIf(f func(uint64) bool) {
ms.getState().AssertMutable()
newLen := 0
for i := 0; i < len(*ms.getOrig()); i++ {
if f((*ms.getOrig())[i]) {
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*ms.getOrig())[newLen] = (*ms.getOrig())[i]
var zero uint64
(*ms.getOrig())[i] = zero
newLen++
}
*ms.getOrig() = (*ms.getOrig())[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (ms UInt64Slice) CopyTo(dest UInt64Slice) {
dest.getState().AssertMutable()
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = copyUint64Slice(*dest.getOrig(), *ms.getOrig())
}
// Equal checks equality with another UInt64Slice
func (ms UInt64Slice) Equal(val UInt64Slice) bool {
return slices.Equal(*ms.getOrig(), *val.getOrig())
}
func copyUint64Slice(dst, src []uint64) []uint64 {
return append(dst[:0], src...)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pcommon // import "go.opentelemetry.io/collector/pdata/pcommon"
import (
"iter"
"go.uber.org/multierr"
"go.opentelemetry.io/collector/pdata/internal"
)
// Map stores a map of string keys to elements of Value type.
//
// Must use NewMap function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Map internal.MapWrapper
// NewMap creates a Map with 0 elements.
func NewMap() Map {
orig := []internal.KeyValue(nil)
return Map(internal.NewMapWrapper(&orig, internal.NewState()))
}
func (m Map) getOrig() *[]internal.KeyValue {
return internal.GetMapOrig(internal.MapWrapper(m))
}
func (m Map) getState() *internal.State {
return internal.GetMapState(internal.MapWrapper(m))
}
func newMap(orig *[]internal.KeyValue, state *internal.State) Map {
return Map(internal.NewMapWrapper(orig, state))
}
// Clear erases any existing entries in this Map instance.
func (m Map) Clear() {
m.getState().AssertMutable()
*m.getOrig() = nil
}
// EnsureCapacity increases the capacity of this Map instance, if necessary,
// to ensure that it can hold at least the number of elements specified by the capacity argument.
func (m Map) EnsureCapacity(capacity int) {
m.getState().AssertMutable()
oldOrig := *m.getOrig()
if capacity <= cap(oldOrig) {
return
}
*m.getOrig() = make([]internal.KeyValue, len(oldOrig), capacity)
copy(*m.getOrig(), oldOrig)
}
// Get returns the Value associated with the key and true. The returned
// Value is not a copy, it is a reference to the value stored in this map.
// It is allowed to modify the returned value using Value.Set* functions.
// Such modification will be applied to the value stored in this map.
// Accessing the returned value after modifying the underlying map
// (removing or adding new values) is an undefined behavior.
//
// If the key does not exist, returns a zero-initialized KeyValue and false.
// Calling any functions on the returned invalid instance may cause a panic.
func (m Map) Get(key string) (Value, bool) {
orig := *m.getOrig()
var value *internal.AnyValue
for i := range orig {
akv := &orig[i]
if akv.Key == key {
value = &akv.Value
break
}
}
return newValue(value, m.getState()), value != nil
}
// Remove removes the entry associated with the key and returns true if the key
// was present in the map, otherwise returns false. Removing an entry
// invalidates any Value previously returned by Get from this Map.
func (m Map) Remove(key string) bool {
m.getState().AssertMutable()
for i := range *m.getOrig() {
akv := &(*m.getOrig())[i]
if akv.Key == key {
*akv = (*m.getOrig())[len(*m.getOrig())-1]
*m.getOrig() = (*m.getOrig())[:len(*m.getOrig())-1]
return true
}
}
return false
}
// RemoveIf removes the entries for which the function in question returns true
func (m Map) RemoveIf(f func(string, Value) bool) {
m.getState().AssertMutable()
newLen := 0
for i := 0; i < len(*m.getOrig()); i++ {
if f((*m.getOrig())[i].Key, newValue(&(*m.getOrig())[i].Value, m.getState())) {
(*m.getOrig())[i] = internal.KeyValue{}
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*m.getOrig())[newLen] = (*m.getOrig())[i]
(*m.getOrig())[i] = internal.KeyValue{}
newLen++
}
*m.getOrig() = (*m.getOrig())[:newLen]
}
// PutEmpty inserts or updates an empty value to the map under given key
// and return the updated/inserted value.
func (m Map) PutEmpty(k string) Value {
m.getState().AssertMutable()
if av, existing := m.Get(k); existing {
av.getOrig().Value = nil
return newValue(av.getOrig(), m.getState())
}
*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k})
return newValue(&(*m.getOrig())[len(*m.getOrig())-1].Value, m.getState())
}
// GetOrPutEmpty returns the Value associated with the key and true (loaded) if the key exists in the map,
// otherwise inserts an empty value to the map under the given key and returns the inserted value
// and false (loaded).
func (m Map) GetOrPutEmpty(k string) (Value, bool) {
m.getState().AssertMutable()
if av, existing := m.Get(k); existing {
return av, true
}
*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k})
return newValue(&(*m.getOrig())[len(*m.getOrig())-1].Value, m.getState()), false
}
// PutStr performs the Insert or Update action. The Value is
// inserted to the map that did not originally have the key. The key/value is
// updated to the map where the key already existed.
func (m Map) PutStr(k, v string) {
m.getState().AssertMutable()
if av, existing := m.Get(k); existing {
av.SetStr(v)
return
}
ov := internal.NewAnyValue_StringValue()
ov.StringValue = v
*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
}
// PutInt performs the Insert or Update action. The int Value is
// inserted to the map that did not originally have the key. The key/value is
// updated to the map where the key already existed.
func (m Map) PutInt(k string, v int64) {
m.getState().AssertMutable()
if av, existing := m.Get(k); existing {
av.SetInt(v)
return
}
ov := internal.NewAnyValue_IntValue()
ov.IntValue = v
*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
}
// PutDouble performs the Insert or Update action. The double Value is
// inserted to the map that did not originally have the key. The key/value is
// updated to the map where the key already existed.
func (m Map) PutDouble(k string, v float64) {
m.getState().AssertMutable()
if av, existing := m.Get(k); existing {
av.SetDouble(v)
return
}
ov := internal.NewAnyValue_DoubleValue()
ov.DoubleValue = v
*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
}
// PutBool performs the Insert or Update action. The bool Value is
// inserted to the map that did not originally have the key. The key/value is
// updated to the map where the key already existed.
func (m Map) PutBool(k string, v bool) {
m.getState().AssertMutable()
if av, existing := m.Get(k); existing {
av.SetBool(v)
return
}
ov := internal.NewAnyValue_BoolValue()
ov.BoolValue = v
*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
}
// PutEmptyBytes inserts or updates an empty byte slice under given key and returns it.
func (m Map) PutEmptyBytes(k string) ByteSlice {
m.getState().AssertMutable()
if av, existing := m.Get(k); existing {
return av.SetEmptyBytes()
}
ov := internal.NewAnyValue_BytesValue()
*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
return ByteSlice(internal.NewByteSliceWrapper(&ov.BytesValue, m.getState()))
}
// PutEmptyMap inserts or updates an empty map under given key and returns it.
func (m Map) PutEmptyMap(k string) Map {
m.getState().AssertMutable()
if av, existing := m.Get(k); existing {
return av.SetEmptyMap()
}
ov := internal.NewAnyValue_KvlistValue()
ov.KvlistValue = internal.NewKeyValueList()
*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
return Map(internal.NewMapWrapper(&ov.KvlistValue.Values, m.getState()))
}
// PutEmptySlice inserts or updates an empty slice under given key and returns it.
func (m Map) PutEmptySlice(k string) Slice {
m.getState().AssertMutable()
if av, existing := m.Get(k); existing {
return av.SetEmptySlice()
}
ov := internal.NewAnyValue_ArrayValue()
ov.ArrayValue = internal.NewArrayValue()
*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})
return Slice(internal.NewSliceWrapper(&ov.ArrayValue.Values, m.getState()))
}
// Len returns the length of this map.
//
// Because the Map is represented internally by a slice of pointers, and the data are comping from the wire,
// it is possible that when iterating using "Range" to get access to fewer elements because nil elements are skipped.
func (m Map) Len() int {
return len(*m.getOrig())
}
// Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.
//
// Example:
//
// sm.Range(func(k string, v Value) bool {
// ...
// })
func (m Map) Range(f func(k string, v Value) bool) {
orig := *m.getOrig()
state := m.getState()
for i := range orig {
kv := &orig[i]
if !f(kv.Key, Value(internal.NewValueWrapper(&kv.Value, state))) {
break
}
}
}
// All returns an iterator over key-value pairs in the Map.
//
// for k, v := range es.All() {
// ... // Do something with key-value pair
// }
func (m Map) All() iter.Seq2[string, Value] {
return func(yield func(string, Value) bool) {
orig := *m.getOrig()
state := m.getState()
for i := range orig {
kv := &orig[i]
if !yield(kv.Key, Value(internal.NewValueWrapper(&kv.Value, state))) {
return
}
}
}
}
// MoveTo moves all key/values from the current map overriding the destination and
// resetting the current instance to its zero value
func (m Map) MoveTo(dest Map) {
m.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if m.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = *m.getOrig()
*m.getOrig() = nil
}
// CopyTo copies all elements from the current map overriding the destination.
func (m Map) CopyTo(dest Map) {
dest.getState().AssertMutable()
if m.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = internal.CopyKeyValueSlice(*dest.getOrig(), *m.getOrig())
}
// AsRaw returns a standard go map representation of this Map.
func (m Map) AsRaw() map[string]any {
rawMap := make(map[string]any, m.Len())
m.Range(func(k string, v Value) bool {
rawMap[k] = v.AsRaw()
return true
})
return rawMap
}
// FromRaw overrides this Map instance from a standard go map.
func (m Map) FromRaw(rawMap map[string]any) error {
m.getState().AssertMutable()
if len(rawMap) == 0 {
*m.getOrig() = nil
return nil
}
var errs error
origs := make([]internal.KeyValue, len(rawMap))
ix := 0
for k, iv := range rawMap {
origs[ix].Key = k
errs = multierr.Append(errs, newValue(&origs[ix].Value, m.getState()).FromRaw(iv))
ix++
}
*m.getOrig() = origs
return errs
}
// Equal checks equality with another Map
func (m Map) Equal(val Map) bool {
if m.Len() != val.Len() {
return false
}
fullEqual := true
m.Range(func(k string, v Value) bool {
vv, ok := val.Get(k)
if !ok {
fullEqual = false
return fullEqual
}
if !v.Equal(vv) {
fullEqual = false
}
return fullEqual
})
return fullEqual
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pcommon // import "go.opentelemetry.io/collector/pdata/pcommon"
import (
"go.uber.org/multierr"
"go.opentelemetry.io/collector/pdata/internal"
)
// AsRaw return []any copy of the Slice.
func (es Slice) AsRaw() []any {
rawSlice := make([]any, 0, es.Len())
for i := 0; i < es.Len(); i++ {
rawSlice = append(rawSlice, es.At(i).AsRaw())
}
return rawSlice
}
// FromRaw copies []any into the Slice.
func (es Slice) FromRaw(rawSlice []any) error {
es.getState().AssertMutable()
if len(rawSlice) == 0 {
*es.getOrig() = nil
return nil
}
var errs error
origs := make([]internal.AnyValue, len(rawSlice))
for ix, iv := range rawSlice {
errs = multierr.Append(errs, newValue(&origs[ix], es.getState()).FromRaw(iv))
}
*es.getOrig() = origs
return errs
}
// Equal checks equality with another Slice
func (es Slice) Equal(val Slice) bool {
if es.Len() != val.Len() {
return false
}
for i := 0; i < es.Len(); i++ {
if !es.At(i).Equal(val.At(i)) {
return false
}
}
return true
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pcommon // import "go.opentelemetry.io/collector/pdata/pcommon"
import (
"encoding/hex"
"go.opentelemetry.io/collector/pdata/internal"
)
var emptySpanID = SpanID([8]byte{})
// SpanID is span identifier.
type SpanID [8]byte
// NewSpanIDEmpty returns a new empty (all zero bytes) SpanID.
func NewSpanIDEmpty() SpanID {
return emptySpanID
}
// String returns string representation of the SpanID.
//
// Important: Don't rely on this method to get a string identifier of SpanID,
// Use hex.EncodeToString explicitly instead.
// This method meant to implement Stringer interface for display purposes only.
func (ms SpanID) String() string {
if ms.IsEmpty() {
return ""
}
return hex.EncodeToString(ms[:])
}
// IsEmpty returns true if id doesn't contain at least one non-zero byte.
func (ms SpanID) IsEmpty() bool {
return internal.SpanID(ms).IsEmpty()
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pcommon // import "go.opentelemetry.io/collector/pdata/pcommon"
import (
"time"
)
// Timestamp is a time specified as UNIX Epoch time in nanoseconds since
// 1970-01-01 00:00:00 +0000 UTC.
type Timestamp uint64
// NewTimestampFromTime constructs a new Timestamp from the provided time.Time.
func NewTimestampFromTime(t time.Time) Timestamp {
return Timestamp(uint64(t.UnixNano()))
}
// AsTime converts this to a time.Time.
func (ts Timestamp) AsTime() time.Time {
return time.Unix(0, int64(ts)).UTC()
}
// String returns the string representation of this in UTC.
func (ts Timestamp) String() string {
return ts.AsTime().String()
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pcommon // import "go.opentelemetry.io/collector/pdata/pcommon"
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// TraceState represents the trace state from the w3c-trace-context.
//
// Must use NewTraceState function to create new instances.
// Important: zero-initialized instance is not valid for use.
type TraceState internal.TraceStateWrapper
func NewTraceState() TraceState {
return TraceState(internal.NewTraceStateWrapper(new(string), internal.NewState()))
}
func (ms TraceState) getOrig() *string {
return internal.GetTraceStateOrig(internal.TraceStateWrapper(ms))
}
func (ms TraceState) getState() *internal.State {
return internal.GetTraceStateState(internal.TraceStateWrapper(ms))
}
// AsRaw returns the string representation of the tracestate in w3c-trace-context format: https://www.w3.org/TR/trace-context/#tracestate-header
func (ms TraceState) AsRaw() string {
return *ms.getOrig()
}
// FromRaw copies the string representation in w3c-trace-context format of the tracestate into this TraceState.
func (ms TraceState) FromRaw(v string) {
ms.getState().AssertMutable()
*ms.getOrig() = v
}
// MoveTo moves the TraceState instance overriding the destination
// and resetting the current instance to its zero value.
func (ms TraceState) MoveTo(dest TraceState) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = *ms.getOrig()
*ms.getOrig() = ""
}
// CopyTo copies the TraceState instance overriding the destination.
func (ms TraceState) CopyTo(dest TraceState) {
dest.getState().AssertMutable()
*dest.getOrig() = *ms.getOrig()
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pcommon // import "go.opentelemetry.io/collector/pdata/pcommon"
import (
"encoding/hex"
"go.opentelemetry.io/collector/pdata/internal"
)
var emptyTraceID = TraceID([16]byte{})
// TraceID is a trace identifier.
type TraceID [16]byte
// NewTraceIDEmpty returns a new empty (all zero bytes) TraceID.
func NewTraceIDEmpty() TraceID {
return emptyTraceID
}
// String returns string representation of the TraceID.
//
// Important: Don't rely on this method to get a string identifier of TraceID.
// Use hex.EncodeToString explicitly instead.
// This method meant to implement Stringer interface for display purposes only.
func (ms TraceID) String() string {
if ms.IsEmpty() {
return ""
}
return hex.EncodeToString(ms[:])
}
// IsEmpty returns true if id doesn't contain at least one non-zero byte.
func (ms TraceID) IsEmpty() bool {
return internal.TraceID(ms).IsEmpty()
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pcommon // import "go.opentelemetry.io/collector/pdata/pcommon"
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"go.opentelemetry.io/collector/pdata/internal"
)
// ValueType specifies the type of Value.
type ValueType int32
const (
ValueTypeEmpty ValueType = iota
ValueTypeStr
ValueTypeInt
ValueTypeDouble
ValueTypeBool
ValueTypeMap
ValueTypeSlice
ValueTypeBytes
)
// String returns the string representation of the ValueType.
func (avt ValueType) String() string {
switch avt {
case ValueTypeEmpty:
return "Empty"
case ValueTypeStr:
return "Str"
case ValueTypeBool:
return "Bool"
case ValueTypeInt:
return "Int"
case ValueTypeDouble:
return "Double"
case ValueTypeMap:
return "Map"
case ValueTypeSlice:
return "Slice"
case ValueTypeBytes:
return "Bytes"
}
return ""
}
// Value is a mutable cell containing any value. Typically used as an element of Map or Slice.
// Must use one of NewValue+ functions below to create new instances.
//
// Intended to be passed by value since internally it is just a pointer to actual
// value representation. For the same reason passing by value and calling setters
// will modify the original, e.g.:
//
// func f1(val Value) { val.SetInt(234) }
// func f2() {
// v := NewValueStr("a string")
// f1(v)
// _ := v.Type() // this will return ValueTypeInt
// }
//
// Important: zero-initialized instance is not valid for use. All Value functions below must
// be called only on instances that are created via NewValue+ functions.
type Value internal.ValueWrapper
// NewValueEmpty creates a new Value with an empty value.
func NewValueEmpty() Value {
return newValue(&internal.AnyValue{}, internal.NewState())
}
// NewValueStr creates a new Value with the given string value.
func NewValueStr(v string) Value {
ov := internal.NewAnyValue_StringValue()
ov.StringValue = v
orig := internal.NewAnyValue()
orig.Value = ov
return newValue(orig, internal.NewState())
}
// NewValueInt creates a new Value with the given int64 value.
func NewValueInt(v int64) Value {
ov := internal.NewAnyValue_IntValue()
ov.IntValue = v
orig := internal.NewAnyValue()
orig.Value = ov
return newValue(orig, internal.NewState())
}
// NewValueDouble creates a new Value with the given float64 value.
func NewValueDouble(v float64) Value {
ov := internal.NewAnyValue_DoubleValue()
ov.DoubleValue = v
orig := internal.NewAnyValue()
orig.Value = ov
return newValue(orig, internal.NewState())
}
// NewValueBool creates a new Value with the given bool value.
func NewValueBool(v bool) Value {
ov := internal.NewAnyValue_BoolValue()
ov.BoolValue = v
orig := internal.NewAnyValue()
orig.Value = ov
return newValue(orig, internal.NewState())
}
// NewValueMap creates a new Value of map type.
func NewValueMap() Value {
ov := internal.NewAnyValue_KvlistValue()
ov.KvlistValue = internal.NewKeyValueList()
orig := internal.NewAnyValue()
orig.Value = ov
return newValue(orig, internal.NewState())
}
// NewValueSlice creates a new Value of array type.
func NewValueSlice() Value {
ov := internal.NewAnyValue_ArrayValue()
ov.ArrayValue = internal.NewArrayValue()
orig := internal.NewAnyValue()
orig.Value = ov
return newValue(orig, internal.NewState())
}
// NewValueBytes creates a new empty Value of byte type.
func NewValueBytes() Value {
ov := internal.NewAnyValue_BytesValue()
orig := internal.NewAnyValue()
orig.Value = ov
return newValue(orig, internal.NewState())
}
func newValue(orig *internal.AnyValue, state *internal.State) Value {
return Value(internal.NewValueWrapper(orig, state))
}
func (v Value) getOrig() *internal.AnyValue {
return internal.GetValueOrig(internal.ValueWrapper(v))
}
func (v Value) getState() *internal.State {
return internal.GetValueState(internal.ValueWrapper(v))
}
// FromRaw sets the value from the given raw value.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) FromRaw(iv any) error {
switch tv := iv.(type) {
case nil:
v.getOrig().Value = nil
case string:
v.SetStr(tv)
case int:
v.SetInt(int64(tv))
case int8:
v.SetInt(int64(tv))
case int16:
v.SetInt(int64(tv))
case int32:
v.SetInt(int64(tv))
case int64:
v.SetInt(tv)
case uint:
v.SetInt(int64(tv))
case uint8:
v.SetInt(int64(tv))
case uint16:
v.SetInt(int64(tv))
case uint32:
v.SetInt(int64(tv))
case uint64:
v.SetInt(int64(tv))
case float32:
v.SetDouble(float64(tv))
case float64:
v.SetDouble(tv)
case bool:
v.SetBool(tv)
case []byte:
v.SetEmptyBytes().FromRaw(tv)
case map[string]any:
return v.SetEmptyMap().FromRaw(tv)
case []any:
return v.SetEmptySlice().FromRaw(tv)
default:
return fmt.Errorf("<Invalid value type %T>", tv)
}
return nil
}
// Type returns the type of the value for this Value.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) Type() ValueType {
switch v.getOrig().Value.(type) {
case *internal.AnyValue_StringValue:
return ValueTypeStr
case *internal.AnyValue_BoolValue:
return ValueTypeBool
case *internal.AnyValue_IntValue:
return ValueTypeInt
case *internal.AnyValue_DoubleValue:
return ValueTypeDouble
case *internal.AnyValue_KvlistValue:
return ValueTypeMap
case *internal.AnyValue_ArrayValue:
return ValueTypeSlice
case *internal.AnyValue_BytesValue:
return ValueTypeBytes
}
return ValueTypeEmpty
}
// Str returns the string value associated with this Value.
// The shorter name is used instead of String to avoid implementing fmt.Stringer interface.
// If the Type() is not ValueTypeStr then returns empty string.
func (v Value) Str() string {
return v.getOrig().GetStringValue()
}
// Int returns the int64 value associated with this Value.
// If the Type() is not ValueTypeInt then returns int64(0).
func (v Value) Int() int64 {
return v.getOrig().GetIntValue()
}
// Double returns the float64 value associated with this Value.
// If the Type() is not ValueTypeDouble then returns float64(0).
func (v Value) Double() float64 {
return v.getOrig().GetDoubleValue()
}
// Bool returns the bool value associated with this Value.
// If the Type() is not ValueTypeBool then returns false.
func (v Value) Bool() bool {
return v.getOrig().GetBoolValue()
}
// Map returns the map value associated with this Value.
// If the function is called on zero-initialized Value or if the Type() is not ValueTypeMap
// then it returns an invalid map. Note that using such map can cause panic.
func (v Value) Map() Map {
kvlist := v.getOrig().GetKvlistValue()
if kvlist == nil {
return Map{}
}
return newMap(&kvlist.Values, internal.GetValueState(internal.ValueWrapper(v)))
}
// Slice returns the slice value associated with this Value.
// If the function is called on zero-initialized Value or if the Type() is not ValueTypeSlice
// then returns an invalid slice. Note that using such slice can cause panic.
func (v Value) Slice() Slice {
arr := v.getOrig().GetArrayValue()
if arr == nil {
return Slice{}
}
return newSlice(&arr.Values, internal.GetValueState(internal.ValueWrapper(v)))
}
// Bytes returns the ByteSlice value associated with this Value.
// If the function is called on zero-initialized Value or if the Type() is not ValueTypeBytes
// then returns an invalid ByteSlice object. Note that using such slice can cause panic.
func (v Value) Bytes() ByteSlice {
bv, ok := v.getOrig().GetValue().(*internal.AnyValue_BytesValue)
if !ok {
return ByteSlice{}
}
return ByteSlice(internal.NewByteSliceWrapper(&bv.BytesValue, internal.GetValueState(internal.ValueWrapper(v))))
}
// SetStr replaces the string value associated with this Value,
// it also changes the type to be ValueTypeStr.
// The shorter name is used instead of SetString to avoid implementing
// fmt.Stringer interface by the corresponding getter method.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) SetStr(sv string) {
v.getState().AssertMutable()
v.getOrig().SetStringValue(sv)
}
// SetInt replaces the int64 value associated with this Value,
// it also changes the type to be ValueTypeInt.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) SetInt(iv int64) {
v.getState().AssertMutable()
v.getOrig().SetIntValue(iv)
}
// SetDouble replaces the float64 value associated with this Value,
// it also changes the type to be ValueTypeDouble.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) SetDouble(dv float64) {
v.getState().AssertMutable()
v.getOrig().SetDoubleValue(dv)
}
// SetBool replaces the bool value associated with this Value,
// it also changes the type to be ValueTypeBool.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) SetBool(bv bool) {
v.getState().AssertMutable()
v.getOrig().SetBoolValue(bv)
}
// SetEmptyBytes sets value to an empty byte slice and returns it.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) SetEmptyBytes() ByteSlice {
v.getState().AssertMutable()
// Delete everything but the AnyValue object itself.
internal.DeleteAnyValue(v.getOrig(), false)
bv := internal.NewAnyValue_BytesValue()
v.getOrig().Value = bv
return ByteSlice(internal.NewByteSliceWrapper(&bv.BytesValue, v.getState()))
}
// SetEmptyMap sets value to an empty map and returns it.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) SetEmptyMap() Map {
v.getState().AssertMutable()
// Delete everything but the AnyValue object itself.
internal.DeleteAnyValue(v.getOrig(), false)
ov := internal.NewAnyValue_KvlistValue()
ov.KvlistValue = internal.NewKeyValueList()
v.getOrig().Value = ov
return newMap(&ov.KvlistValue.Values, v.getState())
}
// SetEmptySlice sets value to an empty slice and returns it.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) SetEmptySlice() Slice {
v.getState().AssertMutable()
// Delete everything but the AnyValue object itself.
internal.DeleteAnyValue(v.getOrig(), false)
ov := internal.NewAnyValue_ArrayValue()
ov.ArrayValue = internal.NewArrayValue()
v.getOrig().Value = ov
return newSlice(&ov.ArrayValue.Values, v.getState())
}
// MoveTo moves the Value from current overriding the destination and
// resetting the current instance to empty value.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) MoveTo(dest Value) {
v.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if v.getOrig() == dest.getOrig() {
return
}
*dest.getOrig() = *v.getOrig()
v.getOrig().Value = nil
}
// CopyTo copies the Value instance overriding the destination.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) CopyTo(dest Value) {
dest.getState().AssertMutable()
internal.CopyAnyValue(dest.getOrig(), v.getOrig())
}
// AsString converts an OTLP Value object of any type to its equivalent string
// representation. This differs from Str which only returns a non-empty value
// if the ValueType is ValueTypeStr.
// Calling this function on zero-initialized Value will cause a panic.
func (v Value) AsString() string {
switch v.Type() {
case ValueTypeEmpty:
return ""
case ValueTypeStr:
return v.Str()
case ValueTypeBool:
return strconv.FormatBool(v.Bool())
case ValueTypeDouble:
return float64AsString(v.Double())
case ValueTypeInt:
return strconv.FormatInt(v.Int(), 10)
case ValueTypeMap:
return marshalJSONNoHTMLEscape(v.Map().AsRaw())
case ValueTypeBytes:
return base64.StdEncoding.EncodeToString(*v.Bytes().getOrig())
case ValueTypeSlice:
return marshalJSONNoHTMLEscape(v.Slice().AsRaw())
default:
return fmt.Sprintf("<Unknown OpenTelemetry attribute value type %q>", v.Type())
}
}
// marshalJSONNoHTMLEscape marshals v as JSON without HTML-escaping "<", ">",
// and "&". This matches the behavior of AsString for ValueTypeStr (which
// returns the raw string) and keeps structured values (maps, slices) free
// of escape sequences like "\u003c" that are only meaningful in HTML contexts.
func marshalJSONNoHTMLEscape(v any) string {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
// Encode cannot fail for the map/slice values produced by AsRaw(), which
// only contain primitive types, so the error is intentionally ignored —
// consistent with the json.Marshal calls it replaces.
_ = enc.Encode(v)
// json.Encoder.Encode always appends a trailing newline; strip it so the
// output matches json.Marshal.
return strings.TrimRight(buf.String(), "\n")
}
// See https://cs.opensource.google/go/go/+/refs/tags/go1.17.7:src/encoding/json/encode.go;l=585.
// This allows us to avoid using reflection.
func float64AsString(f float64) string {
if math.IsNaN(f) {
return "NaN"
}
if math.IsInf(f, 1) {
return "Infinity"
}
if math.IsInf(f, -1) {
return "-Infinity"
}
// Convert as if by ES6 number to string conversion.
// This matches most other JSON generators.
// See golang.org/issue/6384 and golang.org/issue/14135.
// Like fmt %g, but the exponent cutoffs are different
// and exponents themselves are not padded to two digits.
scratch := [64]byte{}
b := scratch[:0]
abs := math.Abs(f)
fmt := byte('f')
if abs != 0 && (abs < 1e-6 || abs >= 1e21) {
fmt = 'e'
}
b = strconv.AppendFloat(b, f, fmt, -1, 64)
if fmt == 'e' {
// clean up e-09 to e-9
n := len(b)
if n >= 4 && b[n-4] == 'e' && b[n-3] == '-' && b[n-2] == '0' {
b[n-2] = b[n-1]
b = b[:n-1]
}
}
return string(b)
}
func (v Value) AsRaw() any {
switch v.Type() {
case ValueTypeEmpty:
return nil
case ValueTypeStr:
return v.Str()
case ValueTypeBool:
return v.Bool()
case ValueTypeDouble:
return v.Double()
case ValueTypeInt:
return v.Int()
case ValueTypeBytes:
return v.Bytes().AsRaw()
case ValueTypeMap:
return v.Map().AsRaw()
case ValueTypeSlice:
return v.Slice().AsRaw()
}
return fmt.Sprintf("<Unknown OpenTelemetry value type %q>", v.Type())
}
func (v Value) Equal(c Value) bool {
if v.Type() != c.Type() {
return false
}
switch v.Type() {
case ValueTypeEmpty:
return true
case ValueTypeStr:
return v.Str() == c.Str()
case ValueTypeBool:
return v.Bool() == c.Bool()
case ValueTypeDouble:
return v.Double() == c.Double()
case ValueTypeInt:
return v.Int() == c.Int()
case ValueTypeBytes:
return v.Bytes().Equal(c.Bytes())
case ValueTypeMap:
return v.Map().Equal(c.Map())
case ValueTypeSlice:
return v.Slice().Equal(c.Slice())
}
return false
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package plog
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// LogRecord are experimental implementation of OpenTelemetry Log Data Model.
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewLogRecord function to create new instances.
// Important: zero-initialized instance is not valid for use.
type LogRecord struct {
orig *internal.LogRecord
state *internal.State
}
func newLogRecord(orig *internal.LogRecord, state *internal.State) LogRecord {
return LogRecord{orig: orig, state: state}
}
// NewLogRecord creates a new empty LogRecord.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewLogRecord() LogRecord {
return newLogRecord(internal.NewLogRecord(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms LogRecord) MoveTo(dest LogRecord) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteLogRecord(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Timestamp returns the timestamp associated with this LogRecord.
func (ms LogRecord) Timestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.TimeUnixNano)
}
// SetTimestamp replaces the timestamp associated with this LogRecord.
func (ms LogRecord) SetTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.TimeUnixNano = uint64(v)
}
// ObservedTimestamp returns the observedtimestamp associated with this LogRecord.
func (ms LogRecord) ObservedTimestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.ObservedTimeUnixNano)
}
// SetObservedTimestamp replaces the observedtimestamp associated with this LogRecord.
func (ms LogRecord) SetObservedTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.ObservedTimeUnixNano = uint64(v)
}
// SeverityNumber returns the severitynumber associated with this LogRecord.
func (ms LogRecord) SeverityNumber() SeverityNumber {
return SeverityNumber(ms.orig.SeverityNumber)
}
// SetSeverityNumber replaces the severitynumber associated with this LogRecord.
func (ms LogRecord) SetSeverityNumber(v SeverityNumber) {
ms.state.AssertMutable()
ms.orig.SeverityNumber = internal.SeverityNumber(v)
}
// SeverityText returns the severitytext associated with this LogRecord.
func (ms LogRecord) SeverityText() string {
return ms.orig.SeverityText
}
// SetSeverityText replaces the severitytext associated with this LogRecord.
func (ms LogRecord) SetSeverityText(v string) {
ms.state.AssertMutable()
ms.orig.SeverityText = v
}
// Body returns the body associated with this LogRecord.
func (ms LogRecord) Body() pcommon.Value {
return pcommon.Value(internal.NewValueWrapper(&ms.orig.Body, ms.state))
}
// Attributes returns the Attributes associated with this LogRecord.
func (ms LogRecord) Attributes() pcommon.Map {
return pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))
}
// DroppedAttributesCount returns the droppedattributescount associated with this LogRecord.
func (ms LogRecord) DroppedAttributesCount() uint32 {
return ms.orig.DroppedAttributesCount
}
// SetDroppedAttributesCount replaces the droppedattributescount associated with this LogRecord.
func (ms LogRecord) SetDroppedAttributesCount(v uint32) {
ms.state.AssertMutable()
ms.orig.DroppedAttributesCount = v
}
// Flags returns the flags associated with this LogRecord.
func (ms LogRecord) Flags() LogRecordFlags {
return LogRecordFlags(ms.orig.Flags)
}
// SetFlags replaces the flags associated with this LogRecord.
func (ms LogRecord) SetFlags(v LogRecordFlags) {
ms.state.AssertMutable()
ms.orig.Flags = uint32(v)
}
// TraceID returns the traceid associated with this LogRecord.
func (ms LogRecord) TraceID() pcommon.TraceID {
return pcommon.TraceID(ms.orig.TraceId)
}
// SetTraceID replaces the traceid associated with this LogRecord.
func (ms LogRecord) SetTraceID(v pcommon.TraceID) {
ms.state.AssertMutable()
ms.orig.TraceId = internal.TraceID(v)
}
// SpanID returns the spanid associated with this LogRecord.
func (ms LogRecord) SpanID() pcommon.SpanID {
return pcommon.SpanID(ms.orig.SpanId)
}
// SetSpanID replaces the spanid associated with this LogRecord.
func (ms LogRecord) SetSpanID(v pcommon.SpanID) {
ms.state.AssertMutable()
ms.orig.SpanId = internal.SpanID(v)
}
// EventName returns the eventname associated with this LogRecord.
func (ms LogRecord) EventName() string {
return ms.orig.EventName
}
// SetEventName replaces the eventname associated with this LogRecord.
func (ms LogRecord) SetEventName(v string) {
ms.state.AssertMutable()
ms.orig.EventName = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms LogRecord) CopyTo(dest LogRecord) {
dest.state.AssertMutable()
internal.CopyLogRecord(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package plog
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// LogRecordSlice logically represents a slice of LogRecord.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewLogRecordSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type LogRecordSlice struct {
orig *[]*internal.LogRecord
state *internal.State
}
func newLogRecordSlice(orig *[]*internal.LogRecord, state *internal.State) LogRecordSlice {
return LogRecordSlice{orig: orig, state: state}
}
// NewLogRecordSlice creates a LogRecordSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewLogRecordSlice() LogRecordSlice {
orig := []*internal.LogRecord(nil)
return newLogRecordSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewLogRecordSlice()".
func (es LogRecordSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es LogRecordSlice) At(i int) LogRecord {
return newLogRecord((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es LogRecordSlice) All() iter.Seq2[int, LogRecord] {
return func(yield func(int, LogRecord) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new LogRecordSlice can be initialized:
//
// es := NewLogRecordSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es LogRecordSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.LogRecord, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty LogRecord.
// It returns the newly added LogRecord.
func (es LogRecordSlice) AppendEmpty() LogRecord {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewLogRecord())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es LogRecordSlice) MoveAndAppendTo(dest LogRecordSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es LogRecordSlice) RemoveIf(f func(LogRecord) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteLogRecord((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es LogRecordSlice) CopyTo(dest LogRecordSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyLogRecordPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the LogRecord elements within LogRecordSlice given the
// provided less function so that two instances of LogRecordSlice
// can be compared.
func (es LogRecordSlice) Sort(less func(a, b LogRecord) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package plog
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Logs is the top-level struct that is propagated through the logs pipeline.
// Use NewLogs to create new instance, zero-initialized instance is not valid for use.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewLogs function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Logs internal.LogsWrapper
func newLogs(orig *internal.ExportLogsServiceRequest, state *internal.State) Logs {
return Logs(internal.NewLogsWrapper(orig, state))
}
// NewLogs creates a new empty Logs.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewLogs() Logs {
return newLogs(internal.NewExportLogsServiceRequest(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Logs) MoveTo(dest Logs) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
internal.DeleteExportLogsServiceRequest(dest.getOrig(), false)
*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()
}
// ResourceLogs returns the ResourceLogs associated with this Logs.
func (ms Logs) ResourceLogs() ResourceLogsSlice {
return newResourceLogsSlice(&ms.getOrig().ResourceLogs, ms.getState())
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Logs) CopyTo(dest Logs) {
dest.getState().AssertMutable()
internal.CopyExportLogsServiceRequest(dest.getOrig(), ms.getOrig())
}
func (ms Logs) getOrig() *internal.ExportLogsServiceRequest {
return internal.GetLogsOrig(internal.LogsWrapper(ms))
}
func (ms Logs) getState() *internal.State {
return internal.GetLogsState(internal.LogsWrapper(ms))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package plog
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ResourceLogs is a collection of logs from a Resource.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewResourceLogs function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ResourceLogs struct {
orig *internal.ResourceLogs
state *internal.State
}
func newResourceLogs(orig *internal.ResourceLogs, state *internal.State) ResourceLogs {
return ResourceLogs{orig: orig, state: state}
}
// NewResourceLogs creates a new empty ResourceLogs.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewResourceLogs() ResourceLogs {
return newResourceLogs(internal.NewResourceLogs(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ResourceLogs) MoveTo(dest ResourceLogs) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteResourceLogs(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Resource returns the resource associated with this ResourceLogs.
func (ms ResourceLogs) Resource() pcommon.Resource {
return pcommon.Resource(internal.NewResourceWrapper(&ms.orig.Resource, ms.state))
}
// ScopeLogs returns the ScopeLogs associated with this ResourceLogs.
func (ms ResourceLogs) ScopeLogs() ScopeLogsSlice {
return newScopeLogsSlice(&ms.orig.ScopeLogs, ms.state)
}
// SchemaUrl returns the schemaurl associated with this ResourceLogs.
func (ms ResourceLogs) SchemaUrl() string {
return ms.orig.SchemaUrl
}
// SetSchemaUrl replaces the schemaurl associated with this ResourceLogs.
func (ms ResourceLogs) SetSchemaUrl(v string) {
ms.state.AssertMutable()
ms.orig.SchemaUrl = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ResourceLogs) CopyTo(dest ResourceLogs) {
dest.state.AssertMutable()
internal.CopyResourceLogs(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package plog
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ResourceLogsSlice logically represents a slice of ResourceLogs.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewResourceLogsSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ResourceLogsSlice struct {
orig *[]*internal.ResourceLogs
state *internal.State
}
func newResourceLogsSlice(orig *[]*internal.ResourceLogs, state *internal.State) ResourceLogsSlice {
return ResourceLogsSlice{orig: orig, state: state}
}
// NewResourceLogsSlice creates a ResourceLogsSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewResourceLogsSlice() ResourceLogsSlice {
orig := []*internal.ResourceLogs(nil)
return newResourceLogsSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewResourceLogsSlice()".
func (es ResourceLogsSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ResourceLogsSlice) At(i int) ResourceLogs {
return newResourceLogs((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ResourceLogsSlice) All() iter.Seq2[int, ResourceLogs] {
return func(yield func(int, ResourceLogs) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ResourceLogsSlice can be initialized:
//
// es := NewResourceLogsSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ResourceLogsSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.ResourceLogs, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty ResourceLogs.
// It returns the newly added ResourceLogs.
func (es ResourceLogsSlice) AppendEmpty() ResourceLogs {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewResourceLogs())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ResourceLogsSlice) MoveAndAppendTo(dest ResourceLogsSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ResourceLogsSlice) RemoveIf(f func(ResourceLogs) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteResourceLogs((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ResourceLogsSlice) CopyTo(dest ResourceLogsSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyResourceLogsPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the ResourceLogs elements within ResourceLogsSlice given the
// provided less function so that two instances of ResourceLogsSlice
// can be compared.
func (es ResourceLogsSlice) Sort(less func(a, b ResourceLogs) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package plog
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ScopeLogs is a collection of logs from a LibraryInstrumentation.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewScopeLogs function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ScopeLogs struct {
orig *internal.ScopeLogs
state *internal.State
}
func newScopeLogs(orig *internal.ScopeLogs, state *internal.State) ScopeLogs {
return ScopeLogs{orig: orig, state: state}
}
// NewScopeLogs creates a new empty ScopeLogs.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewScopeLogs() ScopeLogs {
return newScopeLogs(internal.NewScopeLogs(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ScopeLogs) MoveTo(dest ScopeLogs) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteScopeLogs(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Scope returns the scope associated with this ScopeLogs.
func (ms ScopeLogs) Scope() pcommon.InstrumentationScope {
return pcommon.InstrumentationScope(internal.NewInstrumentationScopeWrapper(&ms.orig.Scope, ms.state))
}
// LogRecords returns the LogRecords associated with this ScopeLogs.
func (ms ScopeLogs) LogRecords() LogRecordSlice {
return newLogRecordSlice(&ms.orig.LogRecords, ms.state)
}
// SchemaUrl returns the schemaurl associated with this ScopeLogs.
func (ms ScopeLogs) SchemaUrl() string {
return ms.orig.SchemaUrl
}
// SetSchemaUrl replaces the schemaurl associated with this ScopeLogs.
func (ms ScopeLogs) SetSchemaUrl(v string) {
ms.state.AssertMutable()
ms.orig.SchemaUrl = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ScopeLogs) CopyTo(dest ScopeLogs) {
dest.state.AssertMutable()
internal.CopyScopeLogs(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package plog
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ScopeLogsSlice logically represents a slice of ScopeLogs.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewScopeLogsSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ScopeLogsSlice struct {
orig *[]*internal.ScopeLogs
state *internal.State
}
func newScopeLogsSlice(orig *[]*internal.ScopeLogs, state *internal.State) ScopeLogsSlice {
return ScopeLogsSlice{orig: orig, state: state}
}
// NewScopeLogsSlice creates a ScopeLogsSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewScopeLogsSlice() ScopeLogsSlice {
orig := []*internal.ScopeLogs(nil)
return newScopeLogsSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewScopeLogsSlice()".
func (es ScopeLogsSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ScopeLogsSlice) At(i int) ScopeLogs {
return newScopeLogs((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ScopeLogsSlice) All() iter.Seq2[int, ScopeLogs] {
return func(yield func(int, ScopeLogs) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ScopeLogsSlice can be initialized:
//
// es := NewScopeLogsSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ScopeLogsSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.ScopeLogs, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty ScopeLogs.
// It returns the newly added ScopeLogs.
func (es ScopeLogsSlice) AppendEmpty() ScopeLogs {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewScopeLogs())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ScopeLogsSlice) MoveAndAppendTo(dest ScopeLogsSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ScopeLogsSlice) RemoveIf(f func(ScopeLogs) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteScopeLogs((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ScopeLogsSlice) CopyTo(dest ScopeLogsSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyScopeLogsPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the ScopeLogs elements within ScopeLogsSlice given the
// provided less function so that two instances of ScopeLogsSlice
// can be compared.
func (es ScopeLogsSlice) Sort(less func(a, b ScopeLogs) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package plog // import "go.opentelemetry.io/collector/pdata/plog"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/otlp"
)
// JSONMarshaler marshals Logs to JSON bytes using the OTLP/JSON format.
type JSONMarshaler struct{}
// MarshalLogs to the OTLP/JSON format.
func (*JSONMarshaler) MarshalLogs(ld Logs) ([]byte, error) {
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
ld.getOrig().MarshalJSON(dest)
if dest.Error() != nil {
return nil, dest.Error()
}
return slices.Clone(dest.Buffer()), nil
}
var _ Unmarshaler = (*JSONUnmarshaler)(nil)
// JSONUnmarshaler unmarshals OTLP/JSON formatted-bytes to Logs.
type JSONUnmarshaler struct {
// prevent unkeyed literal initialization
_ struct{}
// DisallowUnknownFields causes UnmarshalLogs to return an error when the
// input contains JSON object fields that are not defined by the OTLP
// schema. When false (the default), unknown fields are silently ignored.
//
// Warning: enabling this option breaks forwards compatibility with future
// evolutions of the OTLP format, as fields added to the format in newer
// versions will be rejected as unknown.
DisallowUnknownFields bool
}
// UnmarshalLogs from OTLP/JSON format into Logs.
func (u *JSONUnmarshaler) UnmarshalLogs(buf []byte) (Logs, error) {
iter := json.BorrowIterator(buf)
defer json.ReturnIterator(iter)
iter.SetDisallowUnknownFields(u.DisallowUnknownFields)
ld := NewLogs()
ld.getOrig().UnmarshalJSON(iter)
if iter.Error() != nil {
return Logs{}, iter.Error()
}
otlp.MigrateLogs(ld.getOrig().ResourceLogs)
return ld, nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package plog // import "go.opentelemetry.io/collector/pdata/plog"
const isSampledMask = uint32(1)
var DefaultLogRecordFlags = LogRecordFlags(0)
// LogRecordFlags defines flags for the LogRecord. The 8 least significant bits are the trace flags as
// defined in W3C Trace Context specification. 24 most significant bits are reserved and must be set to 0.
type LogRecordFlags uint32
// IsSampled returns true if the LogRecordFlags contains the IsSampled flag.
func (ms LogRecordFlags) IsSampled() bool {
return uint32(ms)&isSampledMask != 0
}
// WithIsSampled returns a new LogRecordFlags, with the IsSampled flag set to the given value.
func (ms LogRecordFlags) WithIsSampled(b bool) LogRecordFlags {
orig := uint32(ms)
if b {
orig |= isSampledMask
} else {
orig &^= isSampledMask
}
return LogRecordFlags(orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package plog // import "go.opentelemetry.io/collector/pdata/plog"
// MarkReadOnly marks the Logs as shared so that no further modifications can be done on it.
func (ms Logs) MarkReadOnly() {
ms.getState().MarkReadOnly()
}
// IsReadOnly returns true if this Logs instance is read-only.
func (ms Logs) IsReadOnly() bool {
return ms.getState().IsReadOnly()
}
// LogRecordCount calculates the total number of log records.
func (ms Logs) LogRecordCount() int {
logCount := 0
rss := ms.ResourceLogs()
for i := 0; i < rss.Len(); i++ {
rs := rss.At(i)
ill := rs.ScopeLogs()
for i := 0; i < ill.Len(); i++ {
logs := ill.At(i)
logCount += logs.LogRecords().Len()
}
}
return logCount
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package plog // import "go.opentelemetry.io/collector/pdata/plog"
var _ MarshalSizer = (*ProtoMarshaler)(nil)
type ProtoMarshaler struct{}
func (e *ProtoMarshaler) MarshalLogs(ld Logs) ([]byte, error) {
size := ld.getOrig().SizeProto()
buf := make([]byte, size)
_ = ld.getOrig().MarshalProto(buf)
return buf, nil
}
func (e *ProtoMarshaler) LogsSize(ld Logs) int {
return ld.getOrig().SizeProto()
}
func (e *ProtoMarshaler) ResourceLogsSize(ld ResourceLogs) int {
return ld.orig.SizeProto()
}
func (e *ProtoMarshaler) ScopeLogsSize(ld ScopeLogs) int {
return ld.orig.SizeProto()
}
func (e *ProtoMarshaler) LogRecordSize(ld LogRecord) int {
return ld.orig.SizeProto()
}
var _ Unmarshaler = (*ProtoUnmarshaler)(nil)
type ProtoUnmarshaler struct{}
func (d *ProtoUnmarshaler) UnmarshalLogs(buf []byte) (Logs, error) {
ld := NewLogs()
err := ld.getOrig().UnmarshalProto(buf)
if err != nil {
return Logs{}, err
}
return ld, nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package plogotlp
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ExportPartialSuccess represents the details of a partially successful export request.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExportPartialSuccess function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExportPartialSuccess struct {
orig *internal.ExportLogsPartialSuccess
state *internal.State
}
func newExportPartialSuccess(orig *internal.ExportLogsPartialSuccess, state *internal.State) ExportPartialSuccess {
return ExportPartialSuccess{orig: orig, state: state}
}
// NewExportPartialSuccess creates a new empty ExportPartialSuccess.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExportPartialSuccess() ExportPartialSuccess {
return newExportPartialSuccess(internal.NewExportLogsPartialSuccess(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExportPartialSuccess) MoveTo(dest ExportPartialSuccess) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExportLogsPartialSuccess(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// RejectedLogRecords returns the rejectedlogrecords associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) RejectedLogRecords() int64 {
return ms.orig.RejectedLogRecords
}
// SetRejectedLogRecords replaces the rejectedlogrecords associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) SetRejectedLogRecords(v int64) {
ms.state.AssertMutable()
ms.orig.RejectedLogRecords = v
}
// ErrorMessage returns the errormessage associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) ErrorMessage() string {
return ms.orig.ErrorMessage
}
// SetErrorMessage replaces the errormessage associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) SetErrorMessage(v string) {
ms.state.AssertMutable()
ms.orig.ErrorMessage = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExportPartialSuccess) CopyTo(dest ExportPartialSuccess) {
dest.state.AssertMutable()
internal.CopyExportLogsPartialSuccess(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package plogotlp
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ExportResponse represents the response for gRPC/HTTP client/server.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExportResponse function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExportResponse struct {
orig *internal.ExportLogsServiceResponse
state *internal.State
}
func newExportResponse(orig *internal.ExportLogsServiceResponse, state *internal.State) ExportResponse {
return ExportResponse{orig: orig, state: state}
}
// NewExportResponse creates a new empty ExportResponse.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExportResponse() ExportResponse {
return newExportResponse(internal.NewExportLogsServiceResponse(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExportResponse) MoveTo(dest ExportResponse) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExportLogsServiceResponse(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// PartialSuccess returns the partialsuccess associated with this ExportResponse.
func (ms ExportResponse) PartialSuccess() ExportPartialSuccess {
return newExportPartialSuccess(&ms.orig.PartialSuccess, ms.state)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExportResponse) CopyTo(dest ExportResponse) {
dest.state.AssertMutable()
internal.CopyExportLogsServiceResponse(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package plogotlp // import "go.opentelemetry.io/collector/pdata/plog/plogotlp"
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/internal/otelgrpc"
"go.opentelemetry.io/collector/pdata/internal/otlp"
)
// GRPCClient is the client API for OTLP-GRPC Logs service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type GRPCClient interface {
// Export plog.Logs to the server.
//
// For performance reasons, it is recommended to keep this RPC
// alive for the entire life of the application.
Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error)
// unexported disallow implementation of the GRPCClient.
unexported()
}
// NewGRPCClient returns a new GRPCClient connected using the given connection.
func NewGRPCClient(cc *grpc.ClientConn) GRPCClient {
return &grpcClient{rawClient: otelgrpc.NewLogsServiceClient(cc)}
}
type grpcClient struct {
rawClient otelgrpc.LogsServiceClient
}
func (c *grpcClient) Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error) {
rsp, err := c.rawClient.Export(ctx, request.orig, opts...)
if err != nil {
return ExportResponse{}, err
}
return ExportResponse{orig: rsp, state: internal.NewState()}, err
}
func (c *grpcClient) unexported() {}
// GRPCServer is the server API for OTLP gRPC LogsService service.
// Implementations MUST embed UnimplementedGRPCServer.
type GRPCServer interface {
// Export is called every time a new request is received.
//
// For performance reasons, it is recommended to keep this RPC
// alive for the entire life of the application.
Export(context.Context, ExportRequest) (ExportResponse, error)
// unexported disallow implementation of the GRPCServer.
unexported()
}
var _ GRPCServer = (*UnimplementedGRPCServer)(nil)
// UnimplementedGRPCServer MUST be embedded to have forward compatible implementations.
type UnimplementedGRPCServer struct{}
func (*UnimplementedGRPCServer) Export(context.Context, ExportRequest) (ExportResponse, error) {
return ExportResponse{}, status.Errorf(codes.Unimplemented, "method Export not implemented")
}
func (*UnimplementedGRPCServer) unexported() {}
// RegisterGRPCServer registers the Server to the grpc.Server.
func RegisterGRPCServer(s *grpc.Server, srv GRPCServer) {
otelgrpc.RegisterLogsServiceServer(s, &rawLogsServer{srv: srv})
}
type rawLogsServer struct {
srv GRPCServer
}
func (s rawLogsServer) Export(ctx context.Context, request *internal.ExportLogsServiceRequest) (*internal.ExportLogsServiceResponse, error) {
otlp.MigrateLogs(request.ResourceLogs)
rsp, err := s.srv.Export(ctx, ExportRequest{orig: request, state: internal.NewState()})
return rsp.orig, err
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package plogotlp // import "go.opentelemetry.io/collector/pdata/plog/plogotlp"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/otlp"
"go.opentelemetry.io/collector/pdata/plog"
)
// ExportRequest represents the request for gRPC/HTTP client/server.
// It's a wrapper for plog.Logs data.
type ExportRequest struct {
orig *internal.ExportLogsServiceRequest
state *internal.State
}
// NewExportRequest returns an empty ExportRequest.
func NewExportRequest() ExportRequest {
return ExportRequest{
orig: &internal.ExportLogsServiceRequest{},
state: internal.NewState(),
}
}
// NewExportRequestFromLogs returns a ExportRequest from plog.Logs.
// Because ExportRequest is a wrapper for plog.Logs,
// any changes to the provided Logs struct will be reflected in the ExportRequest and vice versa.
func NewExportRequestFromLogs(ld plog.Logs) ExportRequest {
return ExportRequest{
orig: internal.GetLogsOrig(internal.LogsWrapper(ld)),
state: internal.GetLogsState(internal.LogsWrapper(ld)),
}
}
// MarshalProto marshals ExportRequest into proto bytes.
func (ms ExportRequest) MarshalProto() ([]byte, error) {
size := ms.orig.SizeProto()
buf := make([]byte, size)
_ = ms.orig.MarshalProto(buf)
return buf, nil
}
// UnmarshalProto unmarshalls ExportRequest from proto bytes.
func (ms ExportRequest) UnmarshalProto(data []byte) error {
err := ms.orig.UnmarshalProto(data)
if err != nil {
return err
}
otlp.MigrateLogs(ms.orig.ResourceLogs)
return nil
}
// MarshalJSON marshals ExportRequest into JSON bytes.
func (ms ExportRequest) MarshalJSON() ([]byte, error) {
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
ms.orig.MarshalJSON(dest)
if dest.Error() != nil {
return nil, dest.Error()
}
return slices.Clone(dest.Buffer()), nil
}
// UnmarshalJSON unmarshalls ExportRequest from JSON bytes.
func (ms ExportRequest) UnmarshalJSON(data []byte) error {
iter := json.BorrowIterator(data)
defer json.ReturnIterator(iter)
ms.orig.UnmarshalJSON(iter)
return iter.Error()
}
func (ms ExportRequest) Logs() plog.Logs {
return plog.Logs(internal.NewLogsWrapper(ms.orig, ms.state))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package plogotlp // import "go.opentelemetry.io/collector/pdata/plog/plogotlp"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal/json"
)
// MarshalProto marshals ExportResponse into proto bytes.
func (ms ExportResponse) MarshalProto() ([]byte, error) {
size := ms.orig.SizeProto()
buf := make([]byte, size)
_ = ms.orig.MarshalProto(buf)
return buf, nil
}
// UnmarshalProto unmarshalls ExportResponse from proto bytes.
func (ms ExportResponse) UnmarshalProto(data []byte) error {
return ms.orig.UnmarshalProto(data)
}
// MarshalJSON marshals ExportResponse into JSON bytes.
func (ms ExportResponse) MarshalJSON() ([]byte, error) {
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
ms.orig.MarshalJSON(dest)
return slices.Clone(dest.Buffer()), dest.Error()
}
// UnmarshalJSON unmarshalls ExportResponse from JSON bytes.
func (ms ExportResponse) UnmarshalJSON(data []byte) error {
iter := json.BorrowIterator(data)
defer json.ReturnIterator(iter)
ms.orig.UnmarshalJSON(iter)
return iter.Error()
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package plog // import "go.opentelemetry.io/collector/pdata/plog"
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// SeverityNumber represents severity number of a log record.
type SeverityNumber int32
const (
SeverityNumberUnspecified = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_UNSPECIFIED)
SeverityNumberTrace = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_TRACE)
SeverityNumberTrace2 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_TRACE2)
SeverityNumberTrace3 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_TRACE3)
SeverityNumberTrace4 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_TRACE4)
SeverityNumberDebug = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_DEBUG)
SeverityNumberDebug2 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_DEBUG2)
SeverityNumberDebug3 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_DEBUG3)
SeverityNumberDebug4 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_DEBUG4)
SeverityNumberInfo = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_INFO)
SeverityNumberInfo2 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_INFO2)
SeverityNumberInfo3 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_INFO3)
SeverityNumberInfo4 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_INFO4)
SeverityNumberWarn = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_WARN)
SeverityNumberWarn2 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_WARN2)
SeverityNumberWarn3 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_WARN3)
SeverityNumberWarn4 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_WARN4)
SeverityNumberError = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_ERROR)
SeverityNumberError2 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_ERROR2)
SeverityNumberError3 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_ERROR3)
SeverityNumberError4 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_ERROR4)
SeverityNumberFatal = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_FATAL)
SeverityNumberFatal2 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_FATAL2)
SeverityNumberFatal3 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_FATAL3)
SeverityNumberFatal4 = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_FATAL4)
)
// String returns the string representation of the SeverityNumber.
func (sn SeverityNumber) String() string {
switch sn {
case SeverityNumberUnspecified:
return "Unspecified"
case SeverityNumberTrace:
return "Trace"
case SeverityNumberTrace2:
return "Trace2"
case SeverityNumberTrace3:
return "Trace3"
case SeverityNumberTrace4:
return "Trace4"
case SeverityNumberDebug:
return "Debug"
case SeverityNumberDebug2:
return "Debug2"
case SeverityNumberDebug3:
return "Debug3"
case SeverityNumberDebug4:
return "Debug4"
case SeverityNumberInfo:
return "Info"
case SeverityNumberInfo2:
return "Info2"
case SeverityNumberInfo3:
return "Info3"
case SeverityNumberInfo4:
return "Info4"
case SeverityNumberWarn:
return "Warn"
case SeverityNumberWarn2:
return "Warn2"
case SeverityNumberWarn3:
return "Warn3"
case SeverityNumberWarn4:
return "Warn4"
case SeverityNumberError:
return "Error"
case SeverityNumberError2:
return "Error2"
case SeverityNumberError3:
return "Error3"
case SeverityNumberError4:
return "Error4"
case SeverityNumberFatal:
return "Fatal"
case SeverityNumberFatal2:
return "Fatal2"
case SeverityNumberFatal3:
return "Fatal3"
case SeverityNumberFatal4:
return "Fatal4"
}
return ""
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetric // import "go.opentelemetry.io/collector/pdata/pmetric"
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// AggregationTemporality defines how a metric aggregator reports aggregated values.
// It describes how those values relate to the time interval over which they are aggregated.
type AggregationTemporality int32
const (
// AggregationTemporalityUnspecified is the default AggregationTemporality, it MUST NOT be used.
AggregationTemporalityUnspecified = AggregationTemporality(internal.AggregationTemporality_AGGREGATION_TEMPORALITY_UNSPECIFIED)
// AggregationTemporalityDelta is a AggregationTemporality for a metric aggregator which reports changes since last report time.
AggregationTemporalityDelta = AggregationTemporality(internal.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA)
// AggregationTemporalityCumulative is a AggregationTemporality for a metric aggregator which reports changes since a fixed start time.
AggregationTemporalityCumulative = AggregationTemporality(internal.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE)
)
// String returns the string representation of the AggregationTemporality.
func (at AggregationTemporality) String() string {
switch at {
case AggregationTemporalityUnspecified:
return "Unspecified"
case AggregationTemporalityDelta:
return "Delta"
case AggregationTemporalityCumulative:
return "Cumulative"
}
return ""
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetric // import "go.opentelemetry.io/collector/pdata/pmetric"
// ExemplarValueType specifies the type of Exemplar measurement value.
type ExemplarValueType int32
const (
// ExemplarValueTypeEmpty means that exemplar value is unset.
ExemplarValueTypeEmpty ExemplarValueType = iota
ExemplarValueTypeInt
ExemplarValueTypeDouble
)
// String returns the string representation of the ExemplarValueType.
func (nt ExemplarValueType) String() string {
switch nt {
case ExemplarValueTypeEmpty:
return "Empty"
case ExemplarValueTypeInt:
return "Int"
case ExemplarValueTypeDouble:
return "Double"
}
return ""
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// Exemplar is a sample input double measurement.
//
// Exemplars also hold information about the environment when the measurement was recorded,
// for example the span and trace ID of the active span when the exemplar was recorded.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExemplar function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Exemplar struct {
orig *internal.Exemplar
state *internal.State
}
func newExemplar(orig *internal.Exemplar, state *internal.State) Exemplar {
return Exemplar{orig: orig, state: state}
}
// NewExemplar creates a new empty Exemplar.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExemplar() Exemplar {
return newExemplar(internal.NewExemplar(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Exemplar) MoveTo(dest Exemplar) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExemplar(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// FilteredAttributes returns the FilteredAttributes associated with this Exemplar.
func (ms Exemplar) FilteredAttributes() pcommon.Map {
return pcommon.Map(internal.NewMapWrapper(&ms.orig.FilteredAttributes, ms.state))
}
// Timestamp returns the timestamp associated with this Exemplar.
func (ms Exemplar) Timestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.TimeUnixNano)
}
// SetTimestamp replaces the timestamp associated with this Exemplar.
func (ms Exemplar) SetTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.TimeUnixNano = uint64(v)
}
// ValueType returns the type of the value for this Exemplar.
// Calling this function on zero-initialized Exemplar will cause a panic.
func (ms Exemplar) ValueType() ExemplarValueType {
switch ms.orig.Value.(type) {
case *internal.Exemplar_AsDouble:
return ExemplarValueTypeDouble
case *internal.Exemplar_AsInt:
return ExemplarValueTypeInt
}
return ExemplarValueTypeEmpty
}
// DoubleValue returns the double associated with this Exemplar.
func (ms Exemplar) DoubleValue() float64 {
return ms.orig.GetAsDouble()
}
// SetDoubleValue replaces the double associated with this Exemplar.
func (ms Exemplar) SetDoubleValue(v float64) {
ms.state.AssertMutable()
ms.orig.SetAsDouble(v)
}
// IntValue returns the int associated with this Exemplar.
func (ms Exemplar) IntValue() int64 {
return ms.orig.GetAsInt()
}
// SetIntValue replaces the int associated with this Exemplar.
func (ms Exemplar) SetIntValue(v int64) {
ms.state.AssertMutable()
ms.orig.SetAsInt(v)
}
// TraceID returns the traceid associated with this Exemplar.
func (ms Exemplar) TraceID() pcommon.TraceID {
return pcommon.TraceID(ms.orig.TraceId)
}
// SetTraceID replaces the traceid associated with this Exemplar.
func (ms Exemplar) SetTraceID(v pcommon.TraceID) {
ms.state.AssertMutable()
ms.orig.TraceId = internal.TraceID(v)
}
// SpanID returns the spanid associated with this Exemplar.
func (ms Exemplar) SpanID() pcommon.SpanID {
return pcommon.SpanID(ms.orig.SpanId)
}
// SetSpanID replaces the spanid associated with this Exemplar.
func (ms Exemplar) SetSpanID(v pcommon.SpanID) {
ms.state.AssertMutable()
ms.orig.SpanId = internal.SpanID(v)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Exemplar) CopyTo(dest Exemplar) {
dest.state.AssertMutable()
internal.CopyExemplar(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"iter"
"go.opentelemetry.io/collector/pdata/internal"
)
// ExemplarSlice logically represents a slice of Exemplar.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewExemplarSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExemplarSlice struct {
orig *[]internal.Exemplar
state *internal.State
}
func newExemplarSlice(orig *[]internal.Exemplar, state *internal.State) ExemplarSlice {
return ExemplarSlice{orig: orig, state: state}
}
// NewExemplarSlice creates a ExemplarSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewExemplarSlice() ExemplarSlice {
orig := []internal.Exemplar(nil)
return newExemplarSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewExemplarSlice()".
func (es ExemplarSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ExemplarSlice) At(i int) Exemplar {
return newExemplar(&(*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ExemplarSlice) All() iter.Seq2[int, Exemplar] {
return func(yield func(int, Exemplar) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ExemplarSlice can be initialized:
//
// es := NewExemplarSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ExemplarSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]internal.Exemplar, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Exemplar.
// It returns the newly added Exemplar.
func (es ExemplarSlice) AppendEmpty() Exemplar {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.Exemplar{})
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ExemplarSlice) MoveAndAppendTo(dest ExemplarSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ExemplarSlice) RemoveIf(f func(Exemplar) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteExemplar(&(*es.orig)[i], false)
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
(*es.orig)[i].Reset()
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ExemplarSlice) CopyTo(dest ExemplarSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyExemplarSlice(*dest.orig, *es.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ExponentialHistogram represents the type of a metric that is calculated by aggregating
// as a ExponentialHistogram of all reported double measurements over a time interval.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExponentialHistogram function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExponentialHistogram struct {
orig *internal.ExponentialHistogram
state *internal.State
}
func newExponentialHistogram(orig *internal.ExponentialHistogram, state *internal.State) ExponentialHistogram {
return ExponentialHistogram{orig: orig, state: state}
}
// NewExponentialHistogram creates a new empty ExponentialHistogram.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExponentialHistogram() ExponentialHistogram {
return newExponentialHistogram(internal.NewExponentialHistogram(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExponentialHistogram) MoveTo(dest ExponentialHistogram) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExponentialHistogram(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// DataPoints returns the DataPoints associated with this ExponentialHistogram.
func (ms ExponentialHistogram) DataPoints() ExponentialHistogramDataPointSlice {
return newExponentialHistogramDataPointSlice(&ms.orig.DataPoints, ms.state)
}
// AggregationTemporality returns the aggregationtemporality associated with this ExponentialHistogram.
func (ms ExponentialHistogram) AggregationTemporality() AggregationTemporality {
return AggregationTemporality(ms.orig.AggregationTemporality)
}
// SetAggregationTemporality replaces the aggregationtemporality associated with this ExponentialHistogram.
func (ms ExponentialHistogram) SetAggregationTemporality(v AggregationTemporality) {
ms.state.AssertMutable()
ms.orig.AggregationTemporality = internal.AggregationTemporality(v)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExponentialHistogram) CopyTo(dest ExponentialHistogram) {
dest.state.AssertMutable()
internal.CopyExponentialHistogram(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ExponentialHistogramDataPoint is a single data point in a timeseries that describes the
// time-varying values of a ExponentialHistogram of double values. A ExponentialHistogram contains
// summary statistics for a population of values, it may optionally contain the
// distribution of those values across a set of buckets.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExponentialHistogramDataPoint function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExponentialHistogramDataPoint struct {
orig *internal.ExponentialHistogramDataPoint
state *internal.State
}
func newExponentialHistogramDataPoint(orig *internal.ExponentialHistogramDataPoint, state *internal.State) ExponentialHistogramDataPoint {
return ExponentialHistogramDataPoint{orig: orig, state: state}
}
// NewExponentialHistogramDataPoint creates a new empty ExponentialHistogramDataPoint.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExponentialHistogramDataPoint() ExponentialHistogramDataPoint {
return newExponentialHistogramDataPoint(internal.NewExponentialHistogramDataPoint(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExponentialHistogramDataPoint) MoveTo(dest ExponentialHistogramDataPoint) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExponentialHistogramDataPoint(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Attributes returns the Attributes associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Attributes() pcommon.Map {
return pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))
}
// StartTimestamp returns the starttimestamp associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) StartTimestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.StartTimeUnixNano)
}
// SetStartTimestamp replaces the starttimestamp associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) SetStartTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.StartTimeUnixNano = uint64(v)
}
// Timestamp returns the timestamp associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Timestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.TimeUnixNano)
}
// SetTimestamp replaces the timestamp associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) SetTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.TimeUnixNano = uint64(v)
}
// Count returns the count associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Count() uint64 {
return ms.orig.Count
}
// SetCount replaces the count associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) SetCount(v uint64) {
ms.state.AssertMutable()
ms.orig.Count = v
}
// Sum returns the sum associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Sum() float64 {
return ms.orig.Sum
}
// HasSum returns true if the ExponentialHistogramDataPoint contains a
// Sum value otherwise.
func (ms ExponentialHistogramDataPoint) HasSum() bool {
return ms.orig.HasSum()
}
// SetSum replaces the sum associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) SetSum(v float64) {
ms.state.AssertMutable()
ms.orig.SetSum(v)
}
// RemoveSum removes the sum associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) RemoveSum() {
ms.state.AssertMutable()
ms.orig.RemoveSum()
}
// Scale returns the scale associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Scale() int32 {
return ms.orig.Scale
}
// SetScale replaces the scale associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) SetScale(v int32) {
ms.state.AssertMutable()
ms.orig.Scale = v
}
// ZeroCount returns the zerocount associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) ZeroCount() uint64 {
return ms.orig.ZeroCount
}
// SetZeroCount replaces the zerocount associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) SetZeroCount(v uint64) {
ms.state.AssertMutable()
ms.orig.ZeroCount = v
}
// Positive returns the positive associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Positive() ExponentialHistogramDataPointBuckets {
return newExponentialHistogramDataPointBuckets(&ms.orig.Positive, ms.state)
}
// Negative returns the negative associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Negative() ExponentialHistogramDataPointBuckets {
return newExponentialHistogramDataPointBuckets(&ms.orig.Negative, ms.state)
}
// Flags returns the flags associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Flags() DataPointFlags {
return DataPointFlags(ms.orig.Flags)
}
// SetFlags replaces the flags associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) SetFlags(v DataPointFlags) {
ms.state.AssertMutable()
ms.orig.Flags = uint32(v)
}
// Exemplars returns the Exemplars associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Exemplars() ExemplarSlice {
return newExemplarSlice(&ms.orig.Exemplars, ms.state)
}
// Min returns the min associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Min() float64 {
return ms.orig.Min
}
// HasMin returns true if the ExponentialHistogramDataPoint contains a
// Min value otherwise.
func (ms ExponentialHistogramDataPoint) HasMin() bool {
return ms.orig.HasMin()
}
// SetMin replaces the min associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) SetMin(v float64) {
ms.state.AssertMutable()
ms.orig.SetMin(v)
}
// RemoveMin removes the min associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) RemoveMin() {
ms.state.AssertMutable()
ms.orig.RemoveMin()
}
// Max returns the max associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) Max() float64 {
return ms.orig.Max
}
// HasMax returns true if the ExponentialHistogramDataPoint contains a
// Max value otherwise.
func (ms ExponentialHistogramDataPoint) HasMax() bool {
return ms.orig.HasMax()
}
// SetMax replaces the max associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) SetMax(v float64) {
ms.state.AssertMutable()
ms.orig.SetMax(v)
}
// RemoveMax removes the max associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) RemoveMax() {
ms.state.AssertMutable()
ms.orig.RemoveMax()
}
// ZeroThreshold returns the zerothreshold associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) ZeroThreshold() float64 {
return ms.orig.ZeroThreshold
}
// SetZeroThreshold replaces the zerothreshold associated with this ExponentialHistogramDataPoint.
func (ms ExponentialHistogramDataPoint) SetZeroThreshold(v float64) {
ms.state.AssertMutable()
ms.orig.ZeroThreshold = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExponentialHistogramDataPoint) CopyTo(dest ExponentialHistogramDataPoint) {
dest.state.AssertMutable()
internal.CopyExponentialHistogramDataPoint(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ExponentialHistogramDataPointBuckets are a set of bucket counts, encoded in a contiguous array of counts.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExponentialHistogramDataPointBuckets function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExponentialHistogramDataPointBuckets struct {
orig *internal.ExponentialHistogramDataPointBuckets
state *internal.State
}
func newExponentialHistogramDataPointBuckets(orig *internal.ExponentialHistogramDataPointBuckets, state *internal.State) ExponentialHistogramDataPointBuckets {
return ExponentialHistogramDataPointBuckets{orig: orig, state: state}
}
// NewExponentialHistogramDataPointBuckets creates a new empty ExponentialHistogramDataPointBuckets.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExponentialHistogramDataPointBuckets() ExponentialHistogramDataPointBuckets {
return newExponentialHistogramDataPointBuckets(internal.NewExponentialHistogramDataPointBuckets(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExponentialHistogramDataPointBuckets) MoveTo(dest ExponentialHistogramDataPointBuckets) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExponentialHistogramDataPointBuckets(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Offset returns the offset associated with this ExponentialHistogramDataPointBuckets.
func (ms ExponentialHistogramDataPointBuckets) Offset() int32 {
return ms.orig.Offset
}
// SetOffset replaces the offset associated with this ExponentialHistogramDataPointBuckets.
func (ms ExponentialHistogramDataPointBuckets) SetOffset(v int32) {
ms.state.AssertMutable()
ms.orig.Offset = v
}
// BucketCounts returns the BucketCounts associated with this ExponentialHistogramDataPointBuckets.
func (ms ExponentialHistogramDataPointBuckets) BucketCounts() pcommon.UInt64Slice {
return pcommon.UInt64Slice(internal.NewUInt64SliceWrapper(&ms.orig.BucketCounts, ms.state))
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExponentialHistogramDataPointBuckets) CopyTo(dest ExponentialHistogramDataPointBuckets) {
dest.state.AssertMutable()
internal.CopyExponentialHistogramDataPointBuckets(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ExponentialHistogramDataPointSlice logically represents a slice of ExponentialHistogramDataPoint.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewExponentialHistogramDataPointSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExponentialHistogramDataPointSlice struct {
orig *[]*internal.ExponentialHistogramDataPoint
state *internal.State
}
func newExponentialHistogramDataPointSlice(orig *[]*internal.ExponentialHistogramDataPoint, state *internal.State) ExponentialHistogramDataPointSlice {
return ExponentialHistogramDataPointSlice{orig: orig, state: state}
}
// NewExponentialHistogramDataPointSlice creates a ExponentialHistogramDataPointSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewExponentialHistogramDataPointSlice() ExponentialHistogramDataPointSlice {
orig := []*internal.ExponentialHistogramDataPoint(nil)
return newExponentialHistogramDataPointSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewExponentialHistogramDataPointSlice()".
func (es ExponentialHistogramDataPointSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ExponentialHistogramDataPointSlice) At(i int) ExponentialHistogramDataPoint {
return newExponentialHistogramDataPoint((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ExponentialHistogramDataPointSlice) All() iter.Seq2[int, ExponentialHistogramDataPoint] {
return func(yield func(int, ExponentialHistogramDataPoint) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ExponentialHistogramDataPointSlice can be initialized:
//
// es := NewExponentialHistogramDataPointSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ExponentialHistogramDataPointSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.ExponentialHistogramDataPoint, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty ExponentialHistogramDataPoint.
// It returns the newly added ExponentialHistogramDataPoint.
func (es ExponentialHistogramDataPointSlice) AppendEmpty() ExponentialHistogramDataPoint {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewExponentialHistogramDataPoint())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ExponentialHistogramDataPointSlice) MoveAndAppendTo(dest ExponentialHistogramDataPointSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ExponentialHistogramDataPointSlice) RemoveIf(f func(ExponentialHistogramDataPoint) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteExponentialHistogramDataPoint((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ExponentialHistogramDataPointSlice) CopyTo(dest ExponentialHistogramDataPointSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyExponentialHistogramDataPointPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the ExponentialHistogramDataPoint elements within ExponentialHistogramDataPointSlice given the
// provided less function so that two instances of ExponentialHistogramDataPointSlice
// can be compared.
func (es ExponentialHistogramDataPointSlice) Sort(less func(a, b ExponentialHistogramDataPoint) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Gauge represents the type of a numeric metric that always exports the "current value" for every data point.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewGauge function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Gauge struct {
orig *internal.Gauge
state *internal.State
}
func newGauge(orig *internal.Gauge, state *internal.State) Gauge {
return Gauge{orig: orig, state: state}
}
// NewGauge creates a new empty Gauge.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewGauge() Gauge {
return newGauge(internal.NewGauge(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Gauge) MoveTo(dest Gauge) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteGauge(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// DataPoints returns the DataPoints associated with this Gauge.
func (ms Gauge) DataPoints() NumberDataPointSlice {
return newNumberDataPointSlice(&ms.orig.DataPoints, ms.state)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Gauge) CopyTo(dest Gauge) {
dest.state.AssertMutable()
internal.CopyGauge(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Histogram represents the type of a metric that is calculated by aggregating as a Histogram of all reported measurements over a time interval.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewHistogram function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Histogram struct {
orig *internal.Histogram
state *internal.State
}
func newHistogram(orig *internal.Histogram, state *internal.State) Histogram {
return Histogram{orig: orig, state: state}
}
// NewHistogram creates a new empty Histogram.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewHistogram() Histogram {
return newHistogram(internal.NewHistogram(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Histogram) MoveTo(dest Histogram) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteHistogram(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// DataPoints returns the DataPoints associated with this Histogram.
func (ms Histogram) DataPoints() HistogramDataPointSlice {
return newHistogramDataPointSlice(&ms.orig.DataPoints, ms.state)
}
// AggregationTemporality returns the aggregationtemporality associated with this Histogram.
func (ms Histogram) AggregationTemporality() AggregationTemporality {
return AggregationTemporality(ms.orig.AggregationTemporality)
}
// SetAggregationTemporality replaces the aggregationtemporality associated with this Histogram.
func (ms Histogram) SetAggregationTemporality(v AggregationTemporality) {
ms.state.AssertMutable()
ms.orig.AggregationTemporality = internal.AggregationTemporality(v)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Histogram) CopyTo(dest Histogram) {
dest.state.AssertMutable()
internal.CopyHistogram(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// HistogramDataPoint is a single data point in a timeseries that describes the time-varying values of a Histogram of values.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewHistogramDataPoint function to create new instances.
// Important: zero-initialized instance is not valid for use.
type HistogramDataPoint struct {
orig *internal.HistogramDataPoint
state *internal.State
}
func newHistogramDataPoint(orig *internal.HistogramDataPoint, state *internal.State) HistogramDataPoint {
return HistogramDataPoint{orig: orig, state: state}
}
// NewHistogramDataPoint creates a new empty HistogramDataPoint.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewHistogramDataPoint() HistogramDataPoint {
return newHistogramDataPoint(internal.NewHistogramDataPoint(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms HistogramDataPoint) MoveTo(dest HistogramDataPoint) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteHistogramDataPoint(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Attributes returns the Attributes associated with this HistogramDataPoint.
func (ms HistogramDataPoint) Attributes() pcommon.Map {
return pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))
}
// StartTimestamp returns the starttimestamp associated with this HistogramDataPoint.
func (ms HistogramDataPoint) StartTimestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.StartTimeUnixNano)
}
// SetStartTimestamp replaces the starttimestamp associated with this HistogramDataPoint.
func (ms HistogramDataPoint) SetStartTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.StartTimeUnixNano = uint64(v)
}
// Timestamp returns the timestamp associated with this HistogramDataPoint.
func (ms HistogramDataPoint) Timestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.TimeUnixNano)
}
// SetTimestamp replaces the timestamp associated with this HistogramDataPoint.
func (ms HistogramDataPoint) SetTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.TimeUnixNano = uint64(v)
}
// Count returns the count associated with this HistogramDataPoint.
func (ms HistogramDataPoint) Count() uint64 {
return ms.orig.Count
}
// SetCount replaces the count associated with this HistogramDataPoint.
func (ms HistogramDataPoint) SetCount(v uint64) {
ms.state.AssertMutable()
ms.orig.Count = v
}
// Sum returns the sum associated with this HistogramDataPoint.
func (ms HistogramDataPoint) Sum() float64 {
return ms.orig.Sum
}
// HasSum returns true if the HistogramDataPoint contains a
// Sum value otherwise.
func (ms HistogramDataPoint) HasSum() bool {
return ms.orig.HasSum()
}
// SetSum replaces the sum associated with this HistogramDataPoint.
func (ms HistogramDataPoint) SetSum(v float64) {
ms.state.AssertMutable()
ms.orig.SetSum(v)
}
// RemoveSum removes the sum associated with this HistogramDataPoint.
func (ms HistogramDataPoint) RemoveSum() {
ms.state.AssertMutable()
ms.orig.RemoveSum()
}
// BucketCounts returns the BucketCounts associated with this HistogramDataPoint.
func (ms HistogramDataPoint) BucketCounts() pcommon.UInt64Slice {
return pcommon.UInt64Slice(internal.NewUInt64SliceWrapper(&ms.orig.BucketCounts, ms.state))
}
// ExplicitBounds returns the ExplicitBounds associated with this HistogramDataPoint.
func (ms HistogramDataPoint) ExplicitBounds() pcommon.Float64Slice {
return pcommon.Float64Slice(internal.NewFloat64SliceWrapper(&ms.orig.ExplicitBounds, ms.state))
}
// Exemplars returns the Exemplars associated with this HistogramDataPoint.
func (ms HistogramDataPoint) Exemplars() ExemplarSlice {
return newExemplarSlice(&ms.orig.Exemplars, ms.state)
}
// Flags returns the flags associated with this HistogramDataPoint.
func (ms HistogramDataPoint) Flags() DataPointFlags {
return DataPointFlags(ms.orig.Flags)
}
// SetFlags replaces the flags associated with this HistogramDataPoint.
func (ms HistogramDataPoint) SetFlags(v DataPointFlags) {
ms.state.AssertMutable()
ms.orig.Flags = uint32(v)
}
// Min returns the min associated with this HistogramDataPoint.
func (ms HistogramDataPoint) Min() float64 {
return ms.orig.Min
}
// HasMin returns true if the HistogramDataPoint contains a
// Min value otherwise.
func (ms HistogramDataPoint) HasMin() bool {
return ms.orig.HasMin()
}
// SetMin replaces the min associated with this HistogramDataPoint.
func (ms HistogramDataPoint) SetMin(v float64) {
ms.state.AssertMutable()
ms.orig.SetMin(v)
}
// RemoveMin removes the min associated with this HistogramDataPoint.
func (ms HistogramDataPoint) RemoveMin() {
ms.state.AssertMutable()
ms.orig.RemoveMin()
}
// Max returns the max associated with this HistogramDataPoint.
func (ms HistogramDataPoint) Max() float64 {
return ms.orig.Max
}
// HasMax returns true if the HistogramDataPoint contains a
// Max value otherwise.
func (ms HistogramDataPoint) HasMax() bool {
return ms.orig.HasMax()
}
// SetMax replaces the max associated with this HistogramDataPoint.
func (ms HistogramDataPoint) SetMax(v float64) {
ms.state.AssertMutable()
ms.orig.SetMax(v)
}
// RemoveMax removes the max associated with this HistogramDataPoint.
func (ms HistogramDataPoint) RemoveMax() {
ms.state.AssertMutable()
ms.orig.RemoveMax()
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms HistogramDataPoint) CopyTo(dest HistogramDataPoint) {
dest.state.AssertMutable()
internal.CopyHistogramDataPoint(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// HistogramDataPointSlice logically represents a slice of HistogramDataPoint.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewHistogramDataPointSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type HistogramDataPointSlice struct {
orig *[]*internal.HistogramDataPoint
state *internal.State
}
func newHistogramDataPointSlice(orig *[]*internal.HistogramDataPoint, state *internal.State) HistogramDataPointSlice {
return HistogramDataPointSlice{orig: orig, state: state}
}
// NewHistogramDataPointSlice creates a HistogramDataPointSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewHistogramDataPointSlice() HistogramDataPointSlice {
orig := []*internal.HistogramDataPoint(nil)
return newHistogramDataPointSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewHistogramDataPointSlice()".
func (es HistogramDataPointSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es HistogramDataPointSlice) At(i int) HistogramDataPoint {
return newHistogramDataPoint((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es HistogramDataPointSlice) All() iter.Seq2[int, HistogramDataPoint] {
return func(yield func(int, HistogramDataPoint) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new HistogramDataPointSlice can be initialized:
//
// es := NewHistogramDataPointSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es HistogramDataPointSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.HistogramDataPoint, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty HistogramDataPoint.
// It returns the newly added HistogramDataPoint.
func (es HistogramDataPointSlice) AppendEmpty() HistogramDataPoint {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewHistogramDataPoint())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es HistogramDataPointSlice) MoveAndAppendTo(dest HistogramDataPointSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es HistogramDataPointSlice) RemoveIf(f func(HistogramDataPoint) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteHistogramDataPoint((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es HistogramDataPointSlice) CopyTo(dest HistogramDataPointSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyHistogramDataPointPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the HistogramDataPoint elements within HistogramDataPointSlice given the
// provided less function so that two instances of HistogramDataPointSlice
// can be compared.
func (es HistogramDataPointSlice) Sort(less func(a, b HistogramDataPoint) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// Metric represents one metric as a collection of datapoints.
// See Metric definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewMetric function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Metric struct {
orig *internal.Metric
state *internal.State
}
func newMetric(orig *internal.Metric, state *internal.State) Metric {
return Metric{orig: orig, state: state}
}
// NewMetric creates a new empty Metric.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewMetric() Metric {
return newMetric(internal.NewMetric(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Metric) MoveTo(dest Metric) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteMetric(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Name returns the name associated with this Metric.
func (ms Metric) Name() string {
return ms.orig.Name
}
// SetName replaces the name associated with this Metric.
func (ms Metric) SetName(v string) {
ms.state.AssertMutable()
ms.orig.Name = v
}
// Description returns the description associated with this Metric.
func (ms Metric) Description() string {
return ms.orig.Description
}
// SetDescription replaces the description associated with this Metric.
func (ms Metric) SetDescription(v string) {
ms.state.AssertMutable()
ms.orig.Description = v
}
// Unit returns the unit associated with this Metric.
func (ms Metric) Unit() string {
return ms.orig.Unit
}
// SetUnit replaces the unit associated with this Metric.
func (ms Metric) SetUnit(v string) {
ms.state.AssertMutable()
ms.orig.Unit = v
}
// Type returns the type of the data for this Metric.
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) Type() MetricType {
switch ms.orig.Data.(type) {
case *internal.Metric_Gauge:
return MetricTypeGauge
case *internal.Metric_Sum:
return MetricTypeSum
case *internal.Metric_Histogram:
return MetricTypeHistogram
case *internal.Metric_ExponentialHistogram:
return MetricTypeExponentialHistogram
case *internal.Metric_Summary:
return MetricTypeSummary
}
return MetricTypeEmpty
}
// Gauge returns the gauge associated with this Metric.
//
// Calling this function when Type() != MetricTypeGauge returns an invalid
// zero-initialized instance of Gauge. Note that using such Gauge instance can cause panic.
//
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) Gauge() Gauge {
v, ok := ms.orig.GetData().(*internal.Metric_Gauge)
if !ok {
return Gauge{}
}
return newGauge(v.Gauge, ms.state)
}
// SetEmptyGauge sets an empty gauge to this Metric.
//
// After this, Type() function will return MetricTypeGauge".
//
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) SetEmptyGauge() Gauge {
ms.state.AssertMutable()
ov := internal.NewMetric_Gauge()
ov.Gauge = internal.NewGauge()
ms.orig.Data = ov
return newGauge(ov.Gauge, ms.state)
}
// Sum returns the sum associated with this Metric.
//
// Calling this function when Type() != MetricTypeSum returns an invalid
// zero-initialized instance of Sum. Note that using such Sum instance can cause panic.
//
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) Sum() Sum {
v, ok := ms.orig.GetData().(*internal.Metric_Sum)
if !ok {
return Sum{}
}
return newSum(v.Sum, ms.state)
}
// SetEmptySum sets an empty sum to this Metric.
//
// After this, Type() function will return MetricTypeSum".
//
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) SetEmptySum() Sum {
ms.state.AssertMutable()
ov := internal.NewMetric_Sum()
ov.Sum = internal.NewSum()
ms.orig.Data = ov
return newSum(ov.Sum, ms.state)
}
// Histogram returns the histogram associated with this Metric.
//
// Calling this function when Type() != MetricTypeHistogram returns an invalid
// zero-initialized instance of Histogram. Note that using such Histogram instance can cause panic.
//
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) Histogram() Histogram {
v, ok := ms.orig.GetData().(*internal.Metric_Histogram)
if !ok {
return Histogram{}
}
return newHistogram(v.Histogram, ms.state)
}
// SetEmptyHistogram sets an empty histogram to this Metric.
//
// After this, Type() function will return MetricTypeHistogram".
//
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) SetEmptyHistogram() Histogram {
ms.state.AssertMutable()
ov := internal.NewMetric_Histogram()
ov.Histogram = internal.NewHistogram()
ms.orig.Data = ov
return newHistogram(ov.Histogram, ms.state)
}
// ExponentialHistogram returns the exponentialhistogram associated with this Metric.
//
// Calling this function when Type() != MetricTypeExponentialHistogram returns an invalid
// zero-initialized instance of ExponentialHistogram. Note that using such ExponentialHistogram instance can cause panic.
//
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) ExponentialHistogram() ExponentialHistogram {
v, ok := ms.orig.GetData().(*internal.Metric_ExponentialHistogram)
if !ok {
return ExponentialHistogram{}
}
return newExponentialHistogram(v.ExponentialHistogram, ms.state)
}
// SetEmptyExponentialHistogram sets an empty exponentialhistogram to this Metric.
//
// After this, Type() function will return MetricTypeExponentialHistogram".
//
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) SetEmptyExponentialHistogram() ExponentialHistogram {
ms.state.AssertMutable()
ov := internal.NewMetric_ExponentialHistogram()
ov.ExponentialHistogram = internal.NewExponentialHistogram()
ms.orig.Data = ov
return newExponentialHistogram(ov.ExponentialHistogram, ms.state)
}
// Summary returns the summary associated with this Metric.
//
// Calling this function when Type() != MetricTypeSummary returns an invalid
// zero-initialized instance of Summary. Note that using such Summary instance can cause panic.
//
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) Summary() Summary {
v, ok := ms.orig.GetData().(*internal.Metric_Summary)
if !ok {
return Summary{}
}
return newSummary(v.Summary, ms.state)
}
// SetEmptySummary sets an empty summary to this Metric.
//
// After this, Type() function will return MetricTypeSummary".
//
// Calling this function on zero-initialized Metric will cause a panic.
func (ms Metric) SetEmptySummary() Summary {
ms.state.AssertMutable()
ov := internal.NewMetric_Summary()
ov.Summary = internal.NewSummary()
ms.orig.Data = ov
return newSummary(ov.Summary, ms.state)
}
// Metadata returns the Metadata associated with this Metric.
func (ms Metric) Metadata() pcommon.Map {
return pcommon.Map(internal.NewMapWrapper(&ms.orig.Metadata, ms.state))
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Metric) CopyTo(dest Metric) {
dest.state.AssertMutable()
internal.CopyMetric(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Metrics is the top-level struct that is propagated through the metrics pipeline.
// Use NewMetrics to create new instance, zero-initialized instance is not valid for use.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewMetrics function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Metrics internal.MetricsWrapper
func newMetrics(orig *internal.ExportMetricsServiceRequest, state *internal.State) Metrics {
return Metrics(internal.NewMetricsWrapper(orig, state))
}
// NewMetrics creates a new empty Metrics.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewMetrics() Metrics {
return newMetrics(internal.NewExportMetricsServiceRequest(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Metrics) MoveTo(dest Metrics) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
internal.DeleteExportMetricsServiceRequest(dest.getOrig(), false)
*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()
}
// ResourceMetrics returns the ResourceMetrics associated with this Metrics.
func (ms Metrics) ResourceMetrics() ResourceMetricsSlice {
return newResourceMetricsSlice(&ms.getOrig().ResourceMetrics, ms.getState())
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Metrics) CopyTo(dest Metrics) {
dest.getState().AssertMutable()
internal.CopyExportMetricsServiceRequest(dest.getOrig(), ms.getOrig())
}
func (ms Metrics) getOrig() *internal.ExportMetricsServiceRequest {
return internal.GetMetricsOrig(internal.MetricsWrapper(ms))
}
func (ms Metrics) getState() *internal.State {
return internal.GetMetricsState(internal.MetricsWrapper(ms))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// MetricSlice logically represents a slice of Metric.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewMetricSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type MetricSlice struct {
orig *[]*internal.Metric
state *internal.State
}
func newMetricSlice(orig *[]*internal.Metric, state *internal.State) MetricSlice {
return MetricSlice{orig: orig, state: state}
}
// NewMetricSlice creates a MetricSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewMetricSlice() MetricSlice {
orig := []*internal.Metric(nil)
return newMetricSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewMetricSlice()".
func (es MetricSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es MetricSlice) At(i int) Metric {
return newMetric((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es MetricSlice) All() iter.Seq2[int, Metric] {
return func(yield func(int, Metric) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new MetricSlice can be initialized:
//
// es := NewMetricSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es MetricSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.Metric, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Metric.
// It returns the newly added Metric.
func (es MetricSlice) AppendEmpty() Metric {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewMetric())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es MetricSlice) MoveAndAppendTo(dest MetricSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es MetricSlice) RemoveIf(f func(Metric) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteMetric((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es MetricSlice) CopyTo(dest MetricSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyMetricPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the Metric elements within MetricSlice given the
// provided less function so that two instances of MetricSlice
// can be compared.
func (es MetricSlice) Sort(less func(a, b Metric) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// NumberDataPoint is a single data point in a timeseries that describes the time-varying value of a number metric.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewNumberDataPoint function to create new instances.
// Important: zero-initialized instance is not valid for use.
type NumberDataPoint struct {
orig *internal.NumberDataPoint
state *internal.State
}
func newNumberDataPoint(orig *internal.NumberDataPoint, state *internal.State) NumberDataPoint {
return NumberDataPoint{orig: orig, state: state}
}
// NewNumberDataPoint creates a new empty NumberDataPoint.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewNumberDataPoint() NumberDataPoint {
return newNumberDataPoint(internal.NewNumberDataPoint(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms NumberDataPoint) MoveTo(dest NumberDataPoint) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteNumberDataPoint(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Attributes returns the Attributes associated with this NumberDataPoint.
func (ms NumberDataPoint) Attributes() pcommon.Map {
return pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))
}
// StartTimestamp returns the starttimestamp associated with this NumberDataPoint.
func (ms NumberDataPoint) StartTimestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.StartTimeUnixNano)
}
// SetStartTimestamp replaces the starttimestamp associated with this NumberDataPoint.
func (ms NumberDataPoint) SetStartTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.StartTimeUnixNano = uint64(v)
}
// Timestamp returns the timestamp associated with this NumberDataPoint.
func (ms NumberDataPoint) Timestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.TimeUnixNano)
}
// SetTimestamp replaces the timestamp associated with this NumberDataPoint.
func (ms NumberDataPoint) SetTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.TimeUnixNano = uint64(v)
}
// ValueType returns the type of the value for this NumberDataPoint.
// Calling this function on zero-initialized NumberDataPoint will cause a panic.
func (ms NumberDataPoint) ValueType() NumberDataPointValueType {
switch ms.orig.Value.(type) {
case *internal.NumberDataPoint_AsDouble:
return NumberDataPointValueTypeDouble
case *internal.NumberDataPoint_AsInt:
return NumberDataPointValueTypeInt
}
return NumberDataPointValueTypeEmpty
}
// DoubleValue returns the double associated with this NumberDataPoint.
func (ms NumberDataPoint) DoubleValue() float64 {
return ms.orig.GetAsDouble()
}
// SetDoubleValue replaces the double associated with this NumberDataPoint.
func (ms NumberDataPoint) SetDoubleValue(v float64) {
ms.state.AssertMutable()
ms.orig.SetAsDouble(v)
}
// IntValue returns the int associated with this NumberDataPoint.
func (ms NumberDataPoint) IntValue() int64 {
return ms.orig.GetAsInt()
}
// SetIntValue replaces the int associated with this NumberDataPoint.
func (ms NumberDataPoint) SetIntValue(v int64) {
ms.state.AssertMutable()
ms.orig.SetAsInt(v)
}
// Exemplars returns the Exemplars associated with this NumberDataPoint.
func (ms NumberDataPoint) Exemplars() ExemplarSlice {
return newExemplarSlice(&ms.orig.Exemplars, ms.state)
}
// Flags returns the flags associated with this NumberDataPoint.
func (ms NumberDataPoint) Flags() DataPointFlags {
return DataPointFlags(ms.orig.Flags)
}
// SetFlags replaces the flags associated with this NumberDataPoint.
func (ms NumberDataPoint) SetFlags(v DataPointFlags) {
ms.state.AssertMutable()
ms.orig.Flags = uint32(v)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms NumberDataPoint) CopyTo(dest NumberDataPoint) {
dest.state.AssertMutable()
internal.CopyNumberDataPoint(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// NumberDataPointSlice logically represents a slice of NumberDataPoint.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewNumberDataPointSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type NumberDataPointSlice struct {
orig *[]*internal.NumberDataPoint
state *internal.State
}
func newNumberDataPointSlice(orig *[]*internal.NumberDataPoint, state *internal.State) NumberDataPointSlice {
return NumberDataPointSlice{orig: orig, state: state}
}
// NewNumberDataPointSlice creates a NumberDataPointSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewNumberDataPointSlice() NumberDataPointSlice {
orig := []*internal.NumberDataPoint(nil)
return newNumberDataPointSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewNumberDataPointSlice()".
func (es NumberDataPointSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es NumberDataPointSlice) At(i int) NumberDataPoint {
return newNumberDataPoint((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es NumberDataPointSlice) All() iter.Seq2[int, NumberDataPoint] {
return func(yield func(int, NumberDataPoint) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new NumberDataPointSlice can be initialized:
//
// es := NewNumberDataPointSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es NumberDataPointSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.NumberDataPoint, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty NumberDataPoint.
// It returns the newly added NumberDataPoint.
func (es NumberDataPointSlice) AppendEmpty() NumberDataPoint {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewNumberDataPoint())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es NumberDataPointSlice) MoveAndAppendTo(dest NumberDataPointSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es NumberDataPointSlice) RemoveIf(f func(NumberDataPoint) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteNumberDataPoint((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es NumberDataPointSlice) CopyTo(dest NumberDataPointSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyNumberDataPointPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the NumberDataPoint elements within NumberDataPointSlice given the
// provided less function so that two instances of NumberDataPointSlice
// can be compared.
func (es NumberDataPointSlice) Sort(less func(a, b NumberDataPoint) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ResourceMetrics is a collection of metrics from a Resource.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewResourceMetrics function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ResourceMetrics struct {
orig *internal.ResourceMetrics
state *internal.State
}
func newResourceMetrics(orig *internal.ResourceMetrics, state *internal.State) ResourceMetrics {
return ResourceMetrics{orig: orig, state: state}
}
// NewResourceMetrics creates a new empty ResourceMetrics.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewResourceMetrics() ResourceMetrics {
return newResourceMetrics(internal.NewResourceMetrics(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ResourceMetrics) MoveTo(dest ResourceMetrics) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteResourceMetrics(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Resource returns the resource associated with this ResourceMetrics.
func (ms ResourceMetrics) Resource() pcommon.Resource {
return pcommon.Resource(internal.NewResourceWrapper(&ms.orig.Resource, ms.state))
}
// ScopeMetrics returns the ScopeMetrics associated with this ResourceMetrics.
func (ms ResourceMetrics) ScopeMetrics() ScopeMetricsSlice {
return newScopeMetricsSlice(&ms.orig.ScopeMetrics, ms.state)
}
// SchemaUrl returns the schemaurl associated with this ResourceMetrics.
func (ms ResourceMetrics) SchemaUrl() string {
return ms.orig.SchemaUrl
}
// SetSchemaUrl replaces the schemaurl associated with this ResourceMetrics.
func (ms ResourceMetrics) SetSchemaUrl(v string) {
ms.state.AssertMutable()
ms.orig.SchemaUrl = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ResourceMetrics) CopyTo(dest ResourceMetrics) {
dest.state.AssertMutable()
internal.CopyResourceMetrics(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ResourceMetricsSlice logically represents a slice of ResourceMetrics.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewResourceMetricsSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ResourceMetricsSlice struct {
orig *[]*internal.ResourceMetrics
state *internal.State
}
func newResourceMetricsSlice(orig *[]*internal.ResourceMetrics, state *internal.State) ResourceMetricsSlice {
return ResourceMetricsSlice{orig: orig, state: state}
}
// NewResourceMetricsSlice creates a ResourceMetricsSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewResourceMetricsSlice() ResourceMetricsSlice {
orig := []*internal.ResourceMetrics(nil)
return newResourceMetricsSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewResourceMetricsSlice()".
func (es ResourceMetricsSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ResourceMetricsSlice) At(i int) ResourceMetrics {
return newResourceMetrics((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ResourceMetricsSlice) All() iter.Seq2[int, ResourceMetrics] {
return func(yield func(int, ResourceMetrics) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ResourceMetricsSlice can be initialized:
//
// es := NewResourceMetricsSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ResourceMetricsSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.ResourceMetrics, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty ResourceMetrics.
// It returns the newly added ResourceMetrics.
func (es ResourceMetricsSlice) AppendEmpty() ResourceMetrics {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewResourceMetrics())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ResourceMetricsSlice) MoveAndAppendTo(dest ResourceMetricsSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ResourceMetricsSlice) RemoveIf(f func(ResourceMetrics) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteResourceMetrics((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ResourceMetricsSlice) CopyTo(dest ResourceMetricsSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyResourceMetricsPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the ResourceMetrics elements within ResourceMetricsSlice given the
// provided less function so that two instances of ResourceMetricsSlice
// can be compared.
func (es ResourceMetricsSlice) Sort(less func(a, b ResourceMetrics) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ScopeMetrics is a collection of metrics from a LibraryInstrumentation.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewScopeMetrics function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ScopeMetrics struct {
orig *internal.ScopeMetrics
state *internal.State
}
func newScopeMetrics(orig *internal.ScopeMetrics, state *internal.State) ScopeMetrics {
return ScopeMetrics{orig: orig, state: state}
}
// NewScopeMetrics creates a new empty ScopeMetrics.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewScopeMetrics() ScopeMetrics {
return newScopeMetrics(internal.NewScopeMetrics(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ScopeMetrics) MoveTo(dest ScopeMetrics) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteScopeMetrics(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Scope returns the scope associated with this ScopeMetrics.
func (ms ScopeMetrics) Scope() pcommon.InstrumentationScope {
return pcommon.InstrumentationScope(internal.NewInstrumentationScopeWrapper(&ms.orig.Scope, ms.state))
}
// Metrics returns the Metrics associated with this ScopeMetrics.
func (ms ScopeMetrics) Metrics() MetricSlice {
return newMetricSlice(&ms.orig.Metrics, ms.state)
}
// SchemaUrl returns the schemaurl associated with this ScopeMetrics.
func (ms ScopeMetrics) SchemaUrl() string {
return ms.orig.SchemaUrl
}
// SetSchemaUrl replaces the schemaurl associated with this ScopeMetrics.
func (ms ScopeMetrics) SetSchemaUrl(v string) {
ms.state.AssertMutable()
ms.orig.SchemaUrl = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ScopeMetrics) CopyTo(dest ScopeMetrics) {
dest.state.AssertMutable()
internal.CopyScopeMetrics(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ScopeMetricsSlice logically represents a slice of ScopeMetrics.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewScopeMetricsSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ScopeMetricsSlice struct {
orig *[]*internal.ScopeMetrics
state *internal.State
}
func newScopeMetricsSlice(orig *[]*internal.ScopeMetrics, state *internal.State) ScopeMetricsSlice {
return ScopeMetricsSlice{orig: orig, state: state}
}
// NewScopeMetricsSlice creates a ScopeMetricsSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewScopeMetricsSlice() ScopeMetricsSlice {
orig := []*internal.ScopeMetrics(nil)
return newScopeMetricsSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewScopeMetricsSlice()".
func (es ScopeMetricsSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ScopeMetricsSlice) At(i int) ScopeMetrics {
return newScopeMetrics((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ScopeMetricsSlice) All() iter.Seq2[int, ScopeMetrics] {
return func(yield func(int, ScopeMetrics) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ScopeMetricsSlice can be initialized:
//
// es := NewScopeMetricsSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ScopeMetricsSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.ScopeMetrics, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty ScopeMetrics.
// It returns the newly added ScopeMetrics.
func (es ScopeMetricsSlice) AppendEmpty() ScopeMetrics {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewScopeMetrics())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ScopeMetricsSlice) MoveAndAppendTo(dest ScopeMetricsSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ScopeMetricsSlice) RemoveIf(f func(ScopeMetrics) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteScopeMetrics((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ScopeMetricsSlice) CopyTo(dest ScopeMetricsSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyScopeMetricsPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the ScopeMetrics elements within ScopeMetricsSlice given the
// provided less function so that two instances of ScopeMetricsSlice
// can be compared.
func (es ScopeMetricsSlice) Sort(less func(a, b ScopeMetrics) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Sum represents the type of a numeric metric that is calculated as a sum of all reported measurements over a time interval.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewSum function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Sum struct {
orig *internal.Sum
state *internal.State
}
func newSum(orig *internal.Sum, state *internal.State) Sum {
return Sum{orig: orig, state: state}
}
// NewSum creates a new empty Sum.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewSum() Sum {
return newSum(internal.NewSum(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Sum) MoveTo(dest Sum) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteSum(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// DataPoints returns the DataPoints associated with this Sum.
func (ms Sum) DataPoints() NumberDataPointSlice {
return newNumberDataPointSlice(&ms.orig.DataPoints, ms.state)
}
// AggregationTemporality returns the aggregationtemporality associated with this Sum.
func (ms Sum) AggregationTemporality() AggregationTemporality {
return AggregationTemporality(ms.orig.AggregationTemporality)
}
// SetAggregationTemporality replaces the aggregationtemporality associated with this Sum.
func (ms Sum) SetAggregationTemporality(v AggregationTemporality) {
ms.state.AssertMutable()
ms.orig.AggregationTemporality = internal.AggregationTemporality(v)
}
// IsMonotonic returns the ismonotonic associated with this Sum.
func (ms Sum) IsMonotonic() bool {
return ms.orig.IsMonotonic
}
// SetIsMonotonic replaces the ismonotonic associated with this Sum.
func (ms Sum) SetIsMonotonic(v bool) {
ms.state.AssertMutable()
ms.orig.IsMonotonic = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Sum) CopyTo(dest Sum) {
dest.state.AssertMutable()
internal.CopySum(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Summary represents the type of a metric that is calculated by aggregating as a Summary of all reported double measurements over a time interval.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewSummary function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Summary struct {
orig *internal.Summary
state *internal.State
}
func newSummary(orig *internal.Summary, state *internal.State) Summary {
return Summary{orig: orig, state: state}
}
// NewSummary creates a new empty Summary.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewSummary() Summary {
return newSummary(internal.NewSummary(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Summary) MoveTo(dest Summary) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteSummary(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// DataPoints returns the DataPoints associated with this Summary.
func (ms Summary) DataPoints() SummaryDataPointSlice {
return newSummaryDataPointSlice(&ms.orig.DataPoints, ms.state)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Summary) CopyTo(dest Summary) {
dest.state.AssertMutable()
internal.CopySummary(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// SummaryDataPoint is a single data point in a timeseries that describes the time-varying values of a Summary of double values.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewSummaryDataPoint function to create new instances.
// Important: zero-initialized instance is not valid for use.
type SummaryDataPoint struct {
orig *internal.SummaryDataPoint
state *internal.State
}
func newSummaryDataPoint(orig *internal.SummaryDataPoint, state *internal.State) SummaryDataPoint {
return SummaryDataPoint{orig: orig, state: state}
}
// NewSummaryDataPoint creates a new empty SummaryDataPoint.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewSummaryDataPoint() SummaryDataPoint {
return newSummaryDataPoint(internal.NewSummaryDataPoint(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms SummaryDataPoint) MoveTo(dest SummaryDataPoint) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteSummaryDataPoint(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Attributes returns the Attributes associated with this SummaryDataPoint.
func (ms SummaryDataPoint) Attributes() pcommon.Map {
return pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))
}
// StartTimestamp returns the starttimestamp associated with this SummaryDataPoint.
func (ms SummaryDataPoint) StartTimestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.StartTimeUnixNano)
}
// SetStartTimestamp replaces the starttimestamp associated with this SummaryDataPoint.
func (ms SummaryDataPoint) SetStartTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.StartTimeUnixNano = uint64(v)
}
// Timestamp returns the timestamp associated with this SummaryDataPoint.
func (ms SummaryDataPoint) Timestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.TimeUnixNano)
}
// SetTimestamp replaces the timestamp associated with this SummaryDataPoint.
func (ms SummaryDataPoint) SetTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.TimeUnixNano = uint64(v)
}
// Count returns the count associated with this SummaryDataPoint.
func (ms SummaryDataPoint) Count() uint64 {
return ms.orig.Count
}
// SetCount replaces the count associated with this SummaryDataPoint.
func (ms SummaryDataPoint) SetCount(v uint64) {
ms.state.AssertMutable()
ms.orig.Count = v
}
// Sum returns the sum associated with this SummaryDataPoint.
func (ms SummaryDataPoint) Sum() float64 {
return ms.orig.Sum
}
// SetSum replaces the sum associated with this SummaryDataPoint.
func (ms SummaryDataPoint) SetSum(v float64) {
ms.state.AssertMutable()
ms.orig.Sum = v
}
// QuantileValues returns the QuantileValues associated with this SummaryDataPoint.
func (ms SummaryDataPoint) QuantileValues() SummaryDataPointValueAtQuantileSlice {
return newSummaryDataPointValueAtQuantileSlice(&ms.orig.QuantileValues, ms.state)
}
// Flags returns the flags associated with this SummaryDataPoint.
func (ms SummaryDataPoint) Flags() DataPointFlags {
return DataPointFlags(ms.orig.Flags)
}
// SetFlags replaces the flags associated with this SummaryDataPoint.
func (ms SummaryDataPoint) SetFlags(v DataPointFlags) {
ms.state.AssertMutable()
ms.orig.Flags = uint32(v)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms SummaryDataPoint) CopyTo(dest SummaryDataPoint) {
dest.state.AssertMutable()
internal.CopySummaryDataPoint(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// SummaryDataPointSlice logically represents a slice of SummaryDataPoint.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewSummaryDataPointSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type SummaryDataPointSlice struct {
orig *[]*internal.SummaryDataPoint
state *internal.State
}
func newSummaryDataPointSlice(orig *[]*internal.SummaryDataPoint, state *internal.State) SummaryDataPointSlice {
return SummaryDataPointSlice{orig: orig, state: state}
}
// NewSummaryDataPointSlice creates a SummaryDataPointSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewSummaryDataPointSlice() SummaryDataPointSlice {
orig := []*internal.SummaryDataPoint(nil)
return newSummaryDataPointSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewSummaryDataPointSlice()".
func (es SummaryDataPointSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es SummaryDataPointSlice) At(i int) SummaryDataPoint {
return newSummaryDataPoint((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es SummaryDataPointSlice) All() iter.Seq2[int, SummaryDataPoint] {
return func(yield func(int, SummaryDataPoint) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new SummaryDataPointSlice can be initialized:
//
// es := NewSummaryDataPointSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es SummaryDataPointSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.SummaryDataPoint, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty SummaryDataPoint.
// It returns the newly added SummaryDataPoint.
func (es SummaryDataPointSlice) AppendEmpty() SummaryDataPoint {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewSummaryDataPoint())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es SummaryDataPointSlice) MoveAndAppendTo(dest SummaryDataPointSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es SummaryDataPointSlice) RemoveIf(f func(SummaryDataPoint) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteSummaryDataPoint((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es SummaryDataPointSlice) CopyTo(dest SummaryDataPointSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopySummaryDataPointPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the SummaryDataPoint elements within SummaryDataPointSlice given the
// provided less function so that two instances of SummaryDataPointSlice
// can be compared.
func (es SummaryDataPointSlice) Sort(less func(a, b SummaryDataPoint) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// SummaryDataPointValueAtQuantile is a quantile value within a Summary data point.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewSummaryDataPointValueAtQuantile function to create new instances.
// Important: zero-initialized instance is not valid for use.
type SummaryDataPointValueAtQuantile struct {
orig *internal.SummaryDataPointValueAtQuantile
state *internal.State
}
func newSummaryDataPointValueAtQuantile(orig *internal.SummaryDataPointValueAtQuantile, state *internal.State) SummaryDataPointValueAtQuantile {
return SummaryDataPointValueAtQuantile{orig: orig, state: state}
}
// NewSummaryDataPointValueAtQuantile creates a new empty SummaryDataPointValueAtQuantile.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewSummaryDataPointValueAtQuantile() SummaryDataPointValueAtQuantile {
return newSummaryDataPointValueAtQuantile(internal.NewSummaryDataPointValueAtQuantile(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms SummaryDataPointValueAtQuantile) MoveTo(dest SummaryDataPointValueAtQuantile) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteSummaryDataPointValueAtQuantile(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Quantile returns the quantile associated with this SummaryDataPointValueAtQuantile.
func (ms SummaryDataPointValueAtQuantile) Quantile() float64 {
return ms.orig.Quantile
}
// SetQuantile replaces the quantile associated with this SummaryDataPointValueAtQuantile.
func (ms SummaryDataPointValueAtQuantile) SetQuantile(v float64) {
ms.state.AssertMutable()
ms.orig.Quantile = v
}
// Value returns the value associated with this SummaryDataPointValueAtQuantile.
func (ms SummaryDataPointValueAtQuantile) Value() float64 {
return ms.orig.Value
}
// SetValue replaces the value associated with this SummaryDataPointValueAtQuantile.
func (ms SummaryDataPointValueAtQuantile) SetValue(v float64) {
ms.state.AssertMutable()
ms.orig.Value = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms SummaryDataPointValueAtQuantile) CopyTo(dest SummaryDataPointValueAtQuantile) {
dest.state.AssertMutable()
internal.CopySummaryDataPointValueAtQuantile(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetric
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// SummaryDataPointValueAtQuantileSlice logically represents a slice of SummaryDataPointValueAtQuantile.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewSummaryDataPointValueAtQuantileSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type SummaryDataPointValueAtQuantileSlice struct {
orig *[]*internal.SummaryDataPointValueAtQuantile
state *internal.State
}
func newSummaryDataPointValueAtQuantileSlice(orig *[]*internal.SummaryDataPointValueAtQuantile, state *internal.State) SummaryDataPointValueAtQuantileSlice {
return SummaryDataPointValueAtQuantileSlice{orig: orig, state: state}
}
// NewSummaryDataPointValueAtQuantileSlice creates a SummaryDataPointValueAtQuantileSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewSummaryDataPointValueAtQuantileSlice() SummaryDataPointValueAtQuantileSlice {
orig := []*internal.SummaryDataPointValueAtQuantile(nil)
return newSummaryDataPointValueAtQuantileSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewSummaryDataPointValueAtQuantileSlice()".
func (es SummaryDataPointValueAtQuantileSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es SummaryDataPointValueAtQuantileSlice) At(i int) SummaryDataPointValueAtQuantile {
return newSummaryDataPointValueAtQuantile((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es SummaryDataPointValueAtQuantileSlice) All() iter.Seq2[int, SummaryDataPointValueAtQuantile] {
return func(yield func(int, SummaryDataPointValueAtQuantile) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new SummaryDataPointValueAtQuantileSlice can be initialized:
//
// es := NewSummaryDataPointValueAtQuantileSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es SummaryDataPointValueAtQuantileSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.SummaryDataPointValueAtQuantile, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty SummaryDataPointValueAtQuantile.
// It returns the newly added SummaryDataPointValueAtQuantile.
func (es SummaryDataPointValueAtQuantileSlice) AppendEmpty() SummaryDataPointValueAtQuantile {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewSummaryDataPointValueAtQuantile())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es SummaryDataPointValueAtQuantileSlice) MoveAndAppendTo(dest SummaryDataPointValueAtQuantileSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es SummaryDataPointValueAtQuantileSlice) RemoveIf(f func(SummaryDataPointValueAtQuantile) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteSummaryDataPointValueAtQuantile((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es SummaryDataPointValueAtQuantileSlice) CopyTo(dest SummaryDataPointValueAtQuantileSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopySummaryDataPointValueAtQuantilePtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the SummaryDataPointValueAtQuantile elements within SummaryDataPointValueAtQuantileSlice given the
// provided less function so that two instances of SummaryDataPointValueAtQuantileSlice
// can be compared.
func (es SummaryDataPointValueAtQuantileSlice) Sort(less func(a, b SummaryDataPointValueAtQuantile) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetric // import "go.opentelemetry.io/collector/pdata/pmetric"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/otlp"
)
var _ Marshaler = (*JSONMarshaler)(nil)
// JSONMarshaler marshals Metrics to JSON bytes using the OTLP/JSON format.
type JSONMarshaler struct{}
// MarshalMetrics to the OTLP/JSON format.
func (*JSONMarshaler) MarshalMetrics(md Metrics) ([]byte, error) {
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
md.getOrig().MarshalJSON(dest)
if dest.Error() != nil {
return nil, dest.Error()
}
return slices.Clone(dest.Buffer()), nil
}
// JSONUnmarshaler unmarshals OTLP/JSON formatted-bytes to Metrics.
type JSONUnmarshaler struct {
// prevent unkeyed literal initialization
_ struct{}
// DisallowUnknownFields causes UnmarshalMetrics to return an error when the
// input contains JSON object fields that are not defined by the OTLP
// schema. When false (the default), unknown fields are silently ignored.
//
// Warning: enabling this option breaks forwards compatibility with future
// evolutions of the OTLP format, as fields added to the format in newer
// versions will be rejected as unknown.
DisallowUnknownFields bool
}
// UnmarshalMetrics from OTLP/JSON format into Metrics.
func (u *JSONUnmarshaler) UnmarshalMetrics(buf []byte) (Metrics, error) {
iter := json.BorrowIterator(buf)
defer json.ReturnIterator(iter)
iter.SetDisallowUnknownFields(u.DisallowUnknownFields)
md := NewMetrics()
md.getOrig().UnmarshalJSON(iter)
if iter.Error() != nil {
return Metrics{}, iter.Error()
}
otlp.MigrateMetrics(md.getOrig().ResourceMetrics)
return md, nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetric // import "go.opentelemetry.io/collector/pdata/pmetric"
const noRecordValueMask = uint32(1)
var DefaultDataPointFlags = DataPointFlags(0)
// DataPointFlags defines how a metric aggregator reports aggregated values.
// It describes how those values relate to the time interval over which they are aggregated.
type DataPointFlags uint32
// NoRecordedValue returns true if the DataPointFlags contains the NoRecordedValue flag.
func (ms DataPointFlags) NoRecordedValue() bool {
return uint32(ms)&noRecordValueMask != 0
}
// WithNoRecordedValue returns a new DataPointFlags, with the NoRecordedValue flag set to the given value.
func (ms DataPointFlags) WithNoRecordedValue(b bool) DataPointFlags {
orig := uint32(ms)
if b {
orig |= noRecordValueMask
} else {
orig &^= noRecordValueMask
}
return DataPointFlags(orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetric // import "go.opentelemetry.io/collector/pdata/pmetric"
// MetricType specifies the type of data in a Metric.
type MetricType int32
const (
// MetricTypeEmpty means that metric type is unset.
MetricTypeEmpty MetricType = iota
MetricTypeGauge
MetricTypeSum
MetricTypeHistogram
MetricTypeExponentialHistogram
MetricTypeSummary
)
// String returns the string representation of the MetricType.
func (mdt MetricType) String() string {
switch mdt {
case MetricTypeEmpty:
return "Empty"
case MetricTypeGauge:
return "Gauge"
case MetricTypeSum:
return "Sum"
case MetricTypeHistogram:
return "Histogram"
case MetricTypeExponentialHistogram:
return "ExponentialHistogram"
case MetricTypeSummary:
return "Summary"
}
return ""
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetric // import "go.opentelemetry.io/collector/pdata/pmetric"
// MarkReadOnly marks the Metrics as shared so that no further modifications can be done on it.
func (ms Metrics) MarkReadOnly() {
ms.getState().MarkReadOnly()
}
// IsReadOnly returns true if this Metrics instance is read-only.
func (ms Metrics) IsReadOnly() bool {
return ms.getState().IsReadOnly()
}
// MetricCount calculates the total number of metrics.
func (ms Metrics) MetricCount() int {
metricCount := 0
rms := ms.ResourceMetrics()
for i := 0; i < rms.Len(); i++ {
rm := rms.At(i)
ilms := rm.ScopeMetrics()
for j := 0; j < ilms.Len(); j++ {
ilm := ilms.At(j)
metricCount += ilm.Metrics().Len()
}
}
return metricCount
}
// DataPointCount calculates the total number of data points.
func (ms Metrics) DataPointCount() (dataPointCount int) {
rms := ms.ResourceMetrics()
for i := 0; i < rms.Len(); i++ {
rm := rms.At(i)
ilms := rm.ScopeMetrics()
for j := 0; j < ilms.Len(); j++ {
ilm := ilms.At(j)
ms := ilm.Metrics()
for k := 0; k < ms.Len(); k++ {
m := ms.At(k)
switch m.Type() {
case MetricTypeGauge:
dataPointCount += m.Gauge().DataPoints().Len()
case MetricTypeSum:
dataPointCount += m.Sum().DataPoints().Len()
case MetricTypeHistogram:
dataPointCount += m.Histogram().DataPoints().Len()
case MetricTypeExponentialHistogram:
dataPointCount += m.ExponentialHistogram().DataPoints().Len()
case MetricTypeSummary:
dataPointCount += m.Summary().DataPoints().Len()
}
}
}
}
return dataPointCount
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetric // import "go.opentelemetry.io/collector/pdata/pmetric"
// NumberDataPointValueType specifies the type of NumberDataPoint value.
type NumberDataPointValueType int32
const (
// NumberDataPointValueTypeEmpty means that data point value is unset.
NumberDataPointValueTypeEmpty NumberDataPointValueType = iota
NumberDataPointValueTypeInt
NumberDataPointValueTypeDouble
)
// String returns the string representation of the NumberDataPointValueType.
func (nt NumberDataPointValueType) String() string {
switch nt {
case NumberDataPointValueTypeEmpty:
return "Empty"
case NumberDataPointValueTypeInt:
return "Int"
case NumberDataPointValueTypeDouble:
return "Double"
}
return ""
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetric // import "go.opentelemetry.io/collector/pdata/pmetric"
var _ MarshalSizer = (*ProtoMarshaler)(nil)
type ProtoMarshaler struct{}
func (e *ProtoMarshaler) MarshalMetrics(md Metrics) ([]byte, error) {
size := md.getOrig().SizeProto()
buf := make([]byte, size)
_ = md.getOrig().MarshalProto(buf)
return buf, nil
}
func (e *ProtoMarshaler) MetricsSize(md Metrics) int {
return md.getOrig().SizeProto()
}
func (e *ProtoMarshaler) ResourceMetricsSize(md ResourceMetrics) int {
return md.orig.SizeProto()
}
func (e *ProtoMarshaler) ScopeMetricsSize(md ScopeMetrics) int {
return md.orig.SizeProto()
}
func (e *ProtoMarshaler) MetricSize(md Metric) int {
return md.orig.SizeProto()
}
func (e *ProtoMarshaler) NumberDataPointSize(md NumberDataPoint) int {
return md.orig.SizeProto()
}
func (e *ProtoMarshaler) SummaryDataPointSize(md SummaryDataPoint) int {
return md.orig.SizeProto()
}
func (e *ProtoMarshaler) HistogramDataPointSize(md HistogramDataPoint) int {
return md.orig.SizeProto()
}
func (e *ProtoMarshaler) ExponentialHistogramDataPointSize(md ExponentialHistogramDataPoint) int {
return md.orig.SizeProto()
}
type ProtoUnmarshaler struct{}
func (d *ProtoUnmarshaler) UnmarshalMetrics(buf []byte) (Metrics, error) {
md := NewMetrics()
err := md.getOrig().UnmarshalProto(buf)
if err != nil {
return Metrics{}, err
}
return md, nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetricotlp
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ExportPartialSuccess represents the details of a partially successful export request.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExportPartialSuccess function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExportPartialSuccess struct {
orig *internal.ExportMetricsPartialSuccess
state *internal.State
}
func newExportPartialSuccess(orig *internal.ExportMetricsPartialSuccess, state *internal.State) ExportPartialSuccess {
return ExportPartialSuccess{orig: orig, state: state}
}
// NewExportPartialSuccess creates a new empty ExportPartialSuccess.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExportPartialSuccess() ExportPartialSuccess {
return newExportPartialSuccess(internal.NewExportMetricsPartialSuccess(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExportPartialSuccess) MoveTo(dest ExportPartialSuccess) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExportMetricsPartialSuccess(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// RejectedDataPoints returns the rejecteddatapoints associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) RejectedDataPoints() int64 {
return ms.orig.RejectedDataPoints
}
// SetRejectedDataPoints replaces the rejecteddatapoints associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) SetRejectedDataPoints(v int64) {
ms.state.AssertMutable()
ms.orig.RejectedDataPoints = v
}
// ErrorMessage returns the errormessage associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) ErrorMessage() string {
return ms.orig.ErrorMessage
}
// SetErrorMessage replaces the errormessage associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) SetErrorMessage(v string) {
ms.state.AssertMutable()
ms.orig.ErrorMessage = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExportPartialSuccess) CopyTo(dest ExportPartialSuccess) {
dest.state.AssertMutable()
internal.CopyExportMetricsPartialSuccess(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pmetricotlp
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ExportResponse represents the response for gRPC/HTTP client/server.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExportResponse function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExportResponse struct {
orig *internal.ExportMetricsServiceResponse
state *internal.State
}
func newExportResponse(orig *internal.ExportMetricsServiceResponse, state *internal.State) ExportResponse {
return ExportResponse{orig: orig, state: state}
}
// NewExportResponse creates a new empty ExportResponse.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExportResponse() ExportResponse {
return newExportResponse(internal.NewExportMetricsServiceResponse(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExportResponse) MoveTo(dest ExportResponse) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExportMetricsServiceResponse(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// PartialSuccess returns the partialsuccess associated with this ExportResponse.
func (ms ExportResponse) PartialSuccess() ExportPartialSuccess {
return newExportPartialSuccess(&ms.orig.PartialSuccess, ms.state)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExportResponse) CopyTo(dest ExportResponse) {
dest.state.AssertMutable()
internal.CopyExportMetricsServiceResponse(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetricotlp // import "go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/internal/otelgrpc"
"go.opentelemetry.io/collector/pdata/internal/otlp"
)
// GRPCClient is the client API for OTLP-GRPC Metrics service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type GRPCClient interface {
// Export pmetric.Metrics to the server.
//
// For performance reasons, it is recommended to keep this RPC
// alive for the entire life of the application.
Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error)
// unexported disallow implementation of the GRPCClient.
unexported()
}
// NewGRPCClient returns a new GRPCClient connected using the given connection.
func NewGRPCClient(cc *grpc.ClientConn) GRPCClient {
return &grpcClient{rawClient: otelgrpc.NewMetricsServiceClient(cc)}
}
type grpcClient struct {
rawClient otelgrpc.MetricsServiceClient
}
func (c *grpcClient) Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error) {
rsp, err := c.rawClient.Export(ctx, request.orig, opts...)
if err != nil {
return ExportResponse{}, err
}
return ExportResponse{orig: rsp, state: internal.NewState()}, err
}
func (c *grpcClient) unexported() {}
// GRPCServer is the server API for OTLP gRPC MetricsService service.
// Implementations MUST embed UnimplementedGRPCServer.
type GRPCServer interface {
// Export is called every time a new request is received.
//
// For performance reasons, it is recommended to keep this RPC
// alive for the entire life of the application.
Export(context.Context, ExportRequest) (ExportResponse, error)
// unexported disallow implementation of the GRPCServer.
unexported()
}
var _ GRPCServer = (*UnimplementedGRPCServer)(nil)
// UnimplementedGRPCServer MUST be embedded to have forward compatible implementations.
type UnimplementedGRPCServer struct{}
func (*UnimplementedGRPCServer) Export(context.Context, ExportRequest) (ExportResponse, error) {
return ExportResponse{}, status.Errorf(codes.Unimplemented, "method Export not implemented")
}
func (*UnimplementedGRPCServer) unexported() {}
// RegisterGRPCServer registers the GRPCServer to the grpc.Server.
func RegisterGRPCServer(s *grpc.Server, srv GRPCServer) {
otelgrpc.RegisterMetricsServiceServer(s, &rawMetricsServer{srv: srv})
}
type rawMetricsServer struct {
srv GRPCServer
}
func (s rawMetricsServer) Export(ctx context.Context, request *internal.ExportMetricsServiceRequest) (*internal.ExportMetricsServiceResponse, error) {
otlp.MigrateMetrics(request.ResourceMetrics)
rsp, err := s.srv.Export(ctx, ExportRequest{orig: request, state: internal.NewState()})
return rsp.orig, err
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetricotlp // import "go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/otlp"
"go.opentelemetry.io/collector/pdata/pmetric"
)
// ExportRequest represents the request for gRPC/HTTP client/server.
// It's a wrapper for pmetric.Metrics data.
type ExportRequest struct {
orig *internal.ExportMetricsServiceRequest
state *internal.State
}
// NewExportRequest returns an empty ExportRequest.
func NewExportRequest() ExportRequest {
return ExportRequest{
orig: &internal.ExportMetricsServiceRequest{},
state: internal.NewState(),
}
}
// NewExportRequestFromMetrics returns a ExportRequest from pmetric.Metrics.
// Because ExportRequest is a wrapper for pmetric.Metrics,
// any changes to the provided Metrics struct will be reflected in the ExportRequest and vice versa.
func NewExportRequestFromMetrics(md pmetric.Metrics) ExportRequest {
return ExportRequest{
orig: internal.GetMetricsOrig(internal.MetricsWrapper(md)),
state: internal.GetMetricsState(internal.MetricsWrapper(md)),
}
}
// MarshalProto marshals ExportRequest into proto bytes.
func (ms ExportRequest) MarshalProto() ([]byte, error) {
size := ms.orig.SizeProto()
buf := make([]byte, size)
_ = ms.orig.MarshalProto(buf)
return buf, nil
}
// UnmarshalProto unmarshalls ExportRequest from proto bytes.
func (ms ExportRequest) UnmarshalProto(data []byte) error {
err := ms.orig.UnmarshalProto(data)
if err != nil {
return err
}
otlp.MigrateMetrics(ms.orig.ResourceMetrics)
return nil
}
// MarshalJSON marshals ExportRequest into JSON bytes.
func (ms ExportRequest) MarshalJSON() ([]byte, error) {
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
ms.orig.MarshalJSON(dest)
if dest.Error() != nil {
return nil, dest.Error()
}
return slices.Clone(dest.Buffer()), nil
}
// UnmarshalJSON unmarshalls ExportRequest from JSON bytes.
func (ms ExportRequest) UnmarshalJSON(data []byte) error {
iter := json.BorrowIterator(data)
defer json.ReturnIterator(iter)
ms.orig.UnmarshalJSON(iter)
return iter.Error()
}
func (ms ExportRequest) Metrics() pmetric.Metrics {
return pmetric.Metrics(internal.NewMetricsWrapper(ms.orig, ms.state))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pmetricotlp // import "go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal/json"
)
// MarshalProto marshals ExportResponse into proto bytes.
func (ms ExportResponse) MarshalProto() ([]byte, error) {
size := ms.orig.SizeProto()
buf := make([]byte, size)
_ = ms.orig.MarshalProto(buf)
return buf, nil
}
// UnmarshalProto unmarshalls ExportResponse from proto bytes.
func (ms ExportResponse) UnmarshalProto(data []byte) error {
return ms.orig.UnmarshalProto(data)
}
// MarshalJSON marshals ExportResponse into JSON bytes.
func (ms ExportResponse) MarshalJSON() ([]byte, error) {
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
ms.orig.MarshalJSON(dest)
return slices.Clone(dest.Buffer()), dest.Error()
}
// UnmarshalJSON unmarshalls ExportResponse from JSON bytes.
func (ms ExportResponse) UnmarshalJSON(data []byte) error {
iter := json.BorrowIterator(data)
defer json.ReturnIterator(iter)
ms.orig.UnmarshalJSON(iter)
return iter.Error()
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"errors"
"fmt"
"math"
"go.opentelemetry.io/collector/pdata/pcommon"
)
type attributable interface {
AttributeIndices() pcommon.Int32Slice
}
// FromAttributeIndices builds a [pcommon.Map] containing the attributes of a
// record.
// The record can be any struct that implements an `AttributeIndices` method.
// Updates made to the return map will not be applied back to the record.
func FromAttributeIndices(table KeyValueAndUnitSlice, record attributable, dic ProfilesDictionary) (pcommon.Map, error) {
m := pcommon.NewMap()
m.EnsureCapacity(record.AttributeIndices().Len())
for i := 0; i < record.AttributeIndices().Len(); i++ {
idx := record.AttributeIndices().At(i)
if idx < 0 || int(idx) >= table.Len() {
return m, fmt.Errorf("attribute index %d out of bounds [0, %d)", idx, table.Len())
}
kv := table.At(int(idx))
keyIdx := kv.KeyStrindex()
if keyIdx < 0 || int(keyIdx) >= dic.StringTable().Len() {
return m, fmt.Errorf("key string index %d out of bounds [0, %d)", keyIdx, dic.StringTable().Len())
}
key := dic.StringTable().At(int(keyIdx))
kv.Value().CopyTo(m.PutEmpty(key))
}
return m, nil
}
var errTooManyAttributeTableEntries = errors.New("too many entries in AttributeTable")
// SetAttribute updates an AttributeTable, adding or providing a value and
// returns its index.
func SetAttribute(table KeyValueAndUnitSlice, attr KeyValueAndUnit) (int32, error) {
for j, a := range table.All() {
if a.Equal(attr) {
if j > math.MaxInt32 {
return 0, errTooManyAttributeTableEntries
}
return int32(j), nil
}
}
if table.Len() >= math.MaxInt32 {
return 0, errTooManyAttributeTableEntries
}
attr.CopyTo(table.AppendEmpty())
return int32(table.Len() - 1), nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/internal/otlp"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// mapKeyValues returns the underlying KeyValue slice of a pcommon.Map.
func mapKeyValues(m pcommon.Map) []internal.KeyValue {
return *internal.GetMapOrig(internal.MapWrapper(m))
}
// resolveProfilesReferences walks through all profiles data after unmarshaling
// and resolves any string_value_ref and key_ref to their actual string values.
// This ensures the pdata API works transparently with referenced strings.
func resolveProfilesReferences(profiles Profiles) error {
return otlp.ResolveProfilesReferences(profiles.getOrig())
}
// resolveAnyValueReference resolves string_value_ref in an AnyValue
func resolveAnyValueReference(dict ProfilesDictionary, anyValue *internal.AnyValue) error {
return otlp.ResolveProfilesAnyValueReference(dict.StringTable().AsRaw(), anyValue)
}
// convertProfilesToReferences walks through all profiles data before marshaling
// and converts string values to references for efficient transmission.
// This builds up the string table in the dictionary and replaces strings with refs.
func convertProfilesToReferences(profiles Profiles) error {
return otlp.ConvertProfilesToReferences(profiles.getOrig())
}
// convertKeyValueToReferences converts string keys and values to references in a KeyValue slice
func convertKeyValueToReferences(getStringIndex func(string) int32, kvs []internal.KeyValue) error {
return otlp.ConvertProfilesKeyValuesToReferences(
func(value string) (int32, error) {
return getStringIndex(value), nil
},
kvs,
)
}
// convertAnyValueToReference converts string values to string_value_ref
func convertAnyValueToReference(getStringIndex func(string) int32, anyValue *internal.AnyValue) error {
return otlp.ConvertProfilesAnyValueToReference(
func(value string) (int32, error) {
return getStringIndex(value), nil
},
anyValue,
)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"math"
"go.opentelemetry.io/collector/pdata/pcommon"
)
const (
fnvOffset64 uint64 = 14695981039346656037
fnvPrime64 uint64 = 1099511628211
negZeroBits uint64 = 1 << 63
)
func mixU64(h, v uint64) uint64 {
h ^= v
h *= fnvPrime64
return h
}
// mixBytes reads the slice in place: ByteSlice.AsRaw would copy, and hashing
// must not allocate per entry.
func mixBytes(h uint64, b pcommon.ByteSlice) uint64 {
for i := 0; i < b.Len(); i++ {
h = mixU64(h, uint64(b.At(i)))
}
return mixU64(h, uint64(b.Len()))
}
func mixString(h uint64, s string) uint64 {
for i := 0; i < len(s); i++ {
h = mixU64(h, uint64(s[i]))
}
return mixU64(h, uint64(len(s)))
}
// hashValue mixes an attribute value into h. It must agree with
// [pcommon.Value.Equal]: values that compare equal must hash equal, or the
// index would file them in different buckets and append a duplicate where the
// linear scan deduped. Two consequences of that contract are non-obvious:
// -0.0 is normalized to +0.0 (Equal compares doubles with ==), and maps are
// combined order-independently (Map.Equal matches by key, not by position).
func hashValue(h uint64, v pcommon.Value) uint64 {
h = mixU64(h, uint64(v.Type()))
switch v.Type() {
case pcommon.ValueTypeStr:
return mixString(h, v.Str())
case pcommon.ValueTypeInt:
return mixU64(h, uint64(v.Int()))
case pcommon.ValueTypeDouble:
bits := math.Float64bits(v.Double())
if bits == negZeroBits {
bits = 0
}
return mixU64(h, bits)
case pcommon.ValueTypeBool:
if v.Bool() {
return mixU64(h, 1)
}
return mixU64(h, 0)
case pcommon.ValueTypeBytes:
return mixBytes(h, v.Bytes())
case pcommon.ValueTypeSlice:
s := v.Slice()
h = mixU64(h, uint64(s.Len()))
for i := 0; i < s.Len(); i++ {
h = hashValue(h, s.At(i))
}
return h
case pcommon.ValueTypeMap:
m := v.Map()
var acc uint64
for k, mv := range m.All() {
acc += hashValue(mixString(fnvOffset64, k), mv)
}
return mixU64(mixU64(h, uint64(m.Len())), acc)
case pcommon.ValueTypeEmpty:
}
return h
}
func hashFunction(fn Function) uint64 {
h := fnvOffset64
h = mixU64(h, uint64(uint32(fn.NameStrindex())))
h = mixU64(h, uint64(uint32(fn.SystemNameStrindex())))
h = mixU64(h, uint64(uint32(fn.FilenameStrindex())))
h = mixU64(h, uint64(fn.StartLine()))
return h
}
func hashMapping(ma Mapping) uint64 {
h := fnvOffset64
h = mixU64(h, ma.MemoryStart())
h = mixU64(h, ma.MemoryLimit())
h = mixU64(h, ma.FileOffset())
h = mixU64(h, uint64(uint32(ma.FilenameStrindex())))
ai := ma.AttributeIndices()
for i := 0; i < ai.Len(); i++ {
h = mixU64(h, uint64(uint32(ai.At(i))))
}
return h
}
func hashLocation(loc Location) uint64 {
h := fnvOffset64
h = mixU64(h, uint64(uint32(loc.MappingIndex())))
h = mixU64(h, loc.Address())
ai := loc.AttributeIndices()
for i := 0; i < ai.Len(); i++ {
h = mixU64(h, uint64(uint32(ai.At(i))))
}
lines := loc.Lines()
for i := 0; i < lines.Len(); i++ {
ln := lines.At(i)
h = mixU64(h, uint64(uint32(ln.FunctionIndex())))
h = mixU64(h, uint64(ln.Line()))
h = mixU64(h, uint64(ln.Column()))
}
return h
}
func hashStack(st Stack) uint64 {
h := fnvOffset64
li := st.LocationIndices()
for i := 0; i < li.Len(); i++ {
h = mixU64(h, uint64(uint32(li.At(i))))
}
return h
}
func hashAttribute(a KeyValueAndUnit) uint64 {
h := fnvOffset64
h = mixU64(h, uint64(uint32(a.KeyStrindex())))
h = mixU64(h, uint64(uint32(a.UnitStrindex())))
h = hashValue(h, a.Value())
return h
}
func hashLink(li Link) uint64 {
h := fnvOffset64
tid := li.TraceID()
for _, b := range tid {
h = mixU64(h, uint64(b))
}
sid := li.SpanID()
for _, b := range sid {
h = mixU64(h, uint64(b))
}
return h
}
// mergeIndex accelerates dictionary dedup during a single MergeTo via per-table hash buckets; the table's Equal stays the dedup arbiter.
type mergeIndex struct {
// maxTableLen is the point at which a dictionary table can no longer grow
// without overflowing an int32 index. Carrying it per index rather than as
// a package-level constant lets tests exercise the overflow guards without
// allocating billions of entries.
maxTableLen int
strings map[string]int32
functions map[uint64][]int32
mappings map[uint64][]int32
locations map[uint64][]int32
stacks map[uint64][]int32
attributes map[uint64][]int32
links map[uint64][]int32
}
func newMergeIndex(dst ProfilesDictionary) *mergeIndex {
mi := &mergeIndex{
maxTableLen: math.MaxInt32,
strings: make(map[string]int32, dst.StringTable().Len()),
functions: make(map[uint64][]int32, dst.FunctionTable().Len()),
mappings: make(map[uint64][]int32, dst.MappingTable().Len()),
locations: make(map[uint64][]int32, dst.LocationTable().Len()),
stacks: make(map[uint64][]int32, dst.StackTable().Len()),
attributes: make(map[uint64][]int32, dst.AttributeTable().Len()),
links: make(map[uint64][]int32, dst.LinkTable().Len()),
}
st := dst.StringTable()
for i := 0; i < st.Len(); i++ {
s := st.At(i)
if _, ok := mi.strings[s]; !ok {
mi.strings[s] = int32(i)
}
}
ft := dst.FunctionTable()
for i := 0; i < ft.Len(); i++ {
h := hashFunction(ft.At(i))
mi.functions[h] = append(mi.functions[h], int32(i))
}
mt := dst.MappingTable()
for i := 0; i < mt.Len(); i++ {
h := hashMapping(mt.At(i))
mi.mappings[h] = append(mi.mappings[h], int32(i))
}
lt := dst.LocationTable()
for i := 0; i < lt.Len(); i++ {
h := hashLocation(lt.At(i))
mi.locations[h] = append(mi.locations[h], int32(i))
}
stkt := dst.StackTable()
for i := 0; i < stkt.Len(); i++ {
h := hashStack(stkt.At(i))
mi.stacks[h] = append(mi.stacks[h], int32(i))
}
at := dst.AttributeTable()
for i := 0; i < at.Len(); i++ {
h := hashAttribute(at.At(i))
mi.attributes[h] = append(mi.attributes[h], int32(i))
}
lkt := dst.LinkTable()
for i := 0; i < lkt.Len(); i++ {
h := hashLink(lkt.At(i))
mi.links[h] = append(mi.links[h], int32(i))
}
return mi
}
func (mi *mergeIndex) setString(table pcommon.StringSlice, val string) (int32, error) {
if idx, ok := mi.strings[val]; ok {
return idx, nil
}
if table.Len() >= mi.maxTableLen {
return 0, errTooManyStringTableEntries
}
table.Append(val)
idx := int32(table.Len() - 1)
mi.strings[val] = idx
return idx, nil
}
func (mi *mergeIndex) setFunction(table FunctionSlice, fn Function) (int32, error) {
h := hashFunction(fn)
for _, idx := range mi.functions[h] {
if table.At(int(idx)).Equal(fn) {
return idx, nil
}
}
if table.Len() >= mi.maxTableLen {
return 0, errTooManyFunctionTableEntries
}
fn.CopyTo(table.AppendEmpty())
idx := int32(table.Len() - 1)
mi.functions[h] = append(mi.functions[h], idx)
return idx, nil
}
func (mi *mergeIndex) setMapping(table MappingSlice, ma Mapping) (int32, error) {
h := hashMapping(ma)
for _, idx := range mi.mappings[h] {
if table.At(int(idx)).Equal(ma) {
return idx, nil
}
}
if table.Len() >= mi.maxTableLen {
return 0, errTooManyMappingTableEntries
}
ma.CopyTo(table.AppendEmpty())
idx := int32(table.Len() - 1)
mi.mappings[h] = append(mi.mappings[h], idx)
return idx, nil
}
func (mi *mergeIndex) setLocation(table LocationSlice, loc Location) (int32, error) {
h := hashLocation(loc)
for _, idx := range mi.locations[h] {
if table.At(int(idx)).Equal(loc) {
return idx, nil
}
}
if table.Len() >= mi.maxTableLen {
return 0, errTooManyLocationTableEntries
}
loc.CopyTo(table.AppendEmpty())
idx := int32(table.Len() - 1)
mi.locations[h] = append(mi.locations[h], idx)
return idx, nil
}
func (mi *mergeIndex) setStack(table StackSlice, st Stack) (int32, error) {
h := hashStack(st)
for _, idx := range mi.stacks[h] {
if table.At(int(idx)).Equal(st) {
return idx, nil
}
}
if table.Len() >= mi.maxTableLen {
return 0, errTooManyStackTableEntries
}
st.CopyTo(table.AppendEmpty())
idx := int32(table.Len() - 1)
mi.stacks[h] = append(mi.stacks[h], idx)
return idx, nil
}
func (mi *mergeIndex) setAttribute(table KeyValueAndUnitSlice, attr KeyValueAndUnit) (int32, error) {
h := hashAttribute(attr)
for _, idx := range mi.attributes[h] {
if table.At(int(idx)).Equal(attr) {
return idx, nil
}
}
if table.Len() >= mi.maxTableLen {
return 0, errTooManyAttributeTableEntries
}
attr.CopyTo(table.AppendEmpty())
idx := int32(table.Len() - 1)
mi.attributes[h] = append(mi.attributes[h], idx)
return idx, nil
}
func (mi *mergeIndex) setLink(table LinkSlice, li Link) (int32, error) {
h := hashLink(li)
for _, idx := range mi.links[h] {
if table.At(int(idx)).Equal(li) {
return idx, nil
}
}
if table.Len() >= mi.maxTableLen {
return 0, errTooManyLinkTableEntries
}
li.CopyTo(table.AppendEmpty())
idx := int32(table.Len() - 1)
mi.links[h] = append(mi.links[h], idx)
return idx, nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "fmt"
// Equal checks equality with another Function
func (fn Function) Equal(val Function) bool {
return fn.NameStrindex() == val.NameStrindex() &&
fn.SystemNameStrindex() == val.SystemNameStrindex() &&
fn.FilenameStrindex() == val.FilenameStrindex() &&
fn.StartLine() == val.StartLine()
}
// switchDictionary updates the Function, switching its indices from one
// dictionary to another.
func (fn Function) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
if fn.NameStrindex() > 0 {
if src.StringTable().Len() <= int(fn.NameStrindex()) {
return fmt.Errorf("invalid name index %d", fn.NameStrindex())
}
idx, err := mi.setString(dst.StringTable(), src.StringTable().At(int(fn.NameStrindex())))
if err != nil {
return fmt.Errorf("couldn't set name: %w", err)
}
fn.SetNameStrindex(idx)
}
if fn.SystemNameStrindex() > 0 {
if src.StringTable().Len() <= int(fn.SystemNameStrindex()) {
return fmt.Errorf("invalid system name index %d", fn.SystemNameStrindex())
}
idx, err := mi.setString(dst.StringTable(), src.StringTable().At(int(fn.SystemNameStrindex())))
if err != nil {
return fmt.Errorf("couldn't set system name: %w", err)
}
fn.SetSystemNameStrindex(idx)
}
if fn.FilenameStrindex() > 0 {
if src.StringTable().Len() <= int(fn.FilenameStrindex()) {
return fmt.Errorf("invalid filename index %d", fn.FilenameStrindex())
}
idx, err := mi.setString(dst.StringTable(), src.StringTable().At(int(fn.FilenameStrindex())))
if err != nil {
return fmt.Errorf("couldn't set filename: %w", err)
}
fn.SetFilenameStrindex(idx)
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"errors"
"math"
)
var errTooManyFunctionTableEntries = errors.New("too many entries in FunctionTable")
// SetFunction updates a FunctionTable, adding or providing a value and returns
// its index.
func SetFunction(table FunctionSlice, fn Function) (int32, error) {
for j, m := range table.All() {
if m.Equal(fn) {
if j > math.MaxInt32 {
return 0, errTooManyFunctionTableEntries
}
return int32(j), nil
}
}
if table.Len() >= math.MaxInt32 {
return 0, errTooManyFunctionTableEntries
}
fn.CopyTo(table.AppendEmpty())
return int32(table.Len() - 1), nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Function describes a function, including its human-readable name, system name, source file, and starting line number in the source.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewFunction function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Function struct {
orig *internal.Function
state *internal.State
}
func newFunction(orig *internal.Function, state *internal.State) Function {
return Function{orig: orig, state: state}
}
// NewFunction creates a new empty Function.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewFunction() Function {
return newFunction(internal.NewFunction(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Function) MoveTo(dest Function) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteFunction(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// NameStrindex returns the namestrindex associated with this Function.
func (ms Function) NameStrindex() int32 {
return ms.orig.NameStrindex
}
// SetNameStrindex replaces the namestrindex associated with this Function.
func (ms Function) SetNameStrindex(v int32) {
ms.state.AssertMutable()
ms.orig.NameStrindex = v
}
// SystemNameStrindex returns the systemnamestrindex associated with this Function.
func (ms Function) SystemNameStrindex() int32 {
return ms.orig.SystemNameStrindex
}
// SetSystemNameStrindex replaces the systemnamestrindex associated with this Function.
func (ms Function) SetSystemNameStrindex(v int32) {
ms.state.AssertMutable()
ms.orig.SystemNameStrindex = v
}
// FilenameStrindex returns the filenamestrindex associated with this Function.
func (ms Function) FilenameStrindex() int32 {
return ms.orig.FilenameStrindex
}
// SetFilenameStrindex replaces the filenamestrindex associated with this Function.
func (ms Function) SetFilenameStrindex(v int32) {
ms.state.AssertMutable()
ms.orig.FilenameStrindex = v
}
// StartLine returns the startline associated with this Function.
func (ms Function) StartLine() int64 {
return ms.orig.StartLine
}
// SetStartLine replaces the startline associated with this Function.
func (ms Function) SetStartLine(v int64) {
ms.state.AssertMutable()
ms.orig.StartLine = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Function) CopyTo(dest Function) {
dest.state.AssertMutable()
internal.CopyFunction(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// FunctionSlice logically represents a slice of Function.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewFunctionSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type FunctionSlice struct {
orig *[]*internal.Function
state *internal.State
}
func newFunctionSlice(orig *[]*internal.Function, state *internal.State) FunctionSlice {
return FunctionSlice{orig: orig, state: state}
}
// NewFunctionSlice creates a FunctionSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewFunctionSlice() FunctionSlice {
orig := []*internal.Function(nil)
return newFunctionSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewFunctionSlice()".
func (es FunctionSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es FunctionSlice) At(i int) Function {
return newFunction((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es FunctionSlice) All() iter.Seq2[int, Function] {
return func(yield func(int, Function) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new FunctionSlice can be initialized:
//
// es := NewFunctionSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es FunctionSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.Function, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Function.
// It returns the newly added Function.
func (es FunctionSlice) AppendEmpty() Function {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewFunction())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es FunctionSlice) MoveAndAppendTo(dest FunctionSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es FunctionSlice) RemoveIf(f func(Function) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteFunction((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es FunctionSlice) CopyTo(dest FunctionSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyFunctionPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the Function elements within FunctionSlice given the
// provided less function so that two instances of FunctionSlice
// can be compared.
func (es FunctionSlice) Sort(less func(a, b Function) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// KeyValueAndUnit represents a custom 'dictionary native'
// style of encoding attributes which is more convenient
// for profiles than opentelemetry.proto.common.v1.KeyValue.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewKeyValueAndUnit function to create new instances.
// Important: zero-initialized instance is not valid for use.
type KeyValueAndUnit struct {
orig *internal.KeyValueAndUnit
state *internal.State
}
func newKeyValueAndUnit(orig *internal.KeyValueAndUnit, state *internal.State) KeyValueAndUnit {
return KeyValueAndUnit{orig: orig, state: state}
}
// NewKeyValueAndUnit creates a new empty KeyValueAndUnit.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewKeyValueAndUnit() KeyValueAndUnit {
return newKeyValueAndUnit(internal.NewKeyValueAndUnit(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms KeyValueAndUnit) MoveTo(dest KeyValueAndUnit) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteKeyValueAndUnit(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// KeyStrindex returns the keystrindex associated with this KeyValueAndUnit.
func (ms KeyValueAndUnit) KeyStrindex() int32 {
return ms.orig.KeyStrindex
}
// SetKeyStrindex replaces the keystrindex associated with this KeyValueAndUnit.
func (ms KeyValueAndUnit) SetKeyStrindex(v int32) {
ms.state.AssertMutable()
ms.orig.KeyStrindex = v
}
// Value returns the value associated with this KeyValueAndUnit.
func (ms KeyValueAndUnit) Value() pcommon.Value {
return pcommon.Value(internal.NewValueWrapper(&ms.orig.Value, ms.state))
}
// UnitStrindex returns the unitstrindex associated with this KeyValueAndUnit.
func (ms KeyValueAndUnit) UnitStrindex() int32 {
return ms.orig.UnitStrindex
}
// SetUnitStrindex replaces the unitstrindex associated with this KeyValueAndUnit.
func (ms KeyValueAndUnit) SetUnitStrindex(v int32) {
ms.state.AssertMutable()
ms.orig.UnitStrindex = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms KeyValueAndUnit) CopyTo(dest KeyValueAndUnit) {
dest.state.AssertMutable()
internal.CopyKeyValueAndUnit(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// KeyValueAndUnitSlice logically represents a slice of KeyValueAndUnit.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewKeyValueAndUnitSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type KeyValueAndUnitSlice struct {
orig *[]*internal.KeyValueAndUnit
state *internal.State
}
func newKeyValueAndUnitSlice(orig *[]*internal.KeyValueAndUnit, state *internal.State) KeyValueAndUnitSlice {
return KeyValueAndUnitSlice{orig: orig, state: state}
}
// NewKeyValueAndUnitSlice creates a KeyValueAndUnitSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewKeyValueAndUnitSlice() KeyValueAndUnitSlice {
orig := []*internal.KeyValueAndUnit(nil)
return newKeyValueAndUnitSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewKeyValueAndUnitSlice()".
func (es KeyValueAndUnitSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es KeyValueAndUnitSlice) At(i int) KeyValueAndUnit {
return newKeyValueAndUnit((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es KeyValueAndUnitSlice) All() iter.Seq2[int, KeyValueAndUnit] {
return func(yield func(int, KeyValueAndUnit) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new KeyValueAndUnitSlice can be initialized:
//
// es := NewKeyValueAndUnitSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es KeyValueAndUnitSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.KeyValueAndUnit, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty KeyValueAndUnit.
// It returns the newly added KeyValueAndUnit.
func (es KeyValueAndUnitSlice) AppendEmpty() KeyValueAndUnit {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewKeyValueAndUnit())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es KeyValueAndUnitSlice) MoveAndAppendTo(dest KeyValueAndUnitSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es KeyValueAndUnitSlice) RemoveIf(f func(KeyValueAndUnit) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteKeyValueAndUnit((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es KeyValueAndUnitSlice) CopyTo(dest KeyValueAndUnitSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyKeyValueAndUnitPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the KeyValueAndUnit elements within KeyValueAndUnitSlice given the
// provided less function so that two instances of KeyValueAndUnitSlice
// can be compared.
func (es KeyValueAndUnitSlice) Sort(less func(a, b KeyValueAndUnit) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Line details a specific line in a source code, linked to a function.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewLine function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Line struct {
orig *internal.Line
state *internal.State
}
func newLine(orig *internal.Line, state *internal.State) Line {
return Line{orig: orig, state: state}
}
// NewLine creates a new empty Line.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewLine() Line {
return newLine(internal.NewLine(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Line) MoveTo(dest Line) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteLine(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// FunctionIndex returns the functionindex associated with this Line.
func (ms Line) FunctionIndex() int32 {
return ms.orig.FunctionIndex
}
// SetFunctionIndex replaces the functionindex associated with this Line.
func (ms Line) SetFunctionIndex(v int32) {
ms.state.AssertMutable()
ms.orig.FunctionIndex = v
}
// Line returns the line associated with this Line.
func (ms Line) Line() int64 {
return ms.orig.Line
}
// SetLine replaces the line associated with this Line.
func (ms Line) SetLine(v int64) {
ms.state.AssertMutable()
ms.orig.Line = v
}
// Column returns the column associated with this Line.
func (ms Line) Column() int64 {
return ms.orig.Column
}
// SetColumn replaces the column associated with this Line.
func (ms Line) SetColumn(v int64) {
ms.state.AssertMutable()
ms.orig.Column = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Line) CopyTo(dest Line) {
dest.state.AssertMutable()
internal.CopyLine(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// LineSlice logically represents a slice of Line.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewLineSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type LineSlice struct {
orig *[]*internal.Line
state *internal.State
}
func newLineSlice(orig *[]*internal.Line, state *internal.State) LineSlice {
return LineSlice{orig: orig, state: state}
}
// NewLineSlice creates a LineSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewLineSlice() LineSlice {
orig := []*internal.Line(nil)
return newLineSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewLineSlice()".
func (es LineSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es LineSlice) At(i int) Line {
return newLine((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es LineSlice) All() iter.Seq2[int, Line] {
return func(yield func(int, Line) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new LineSlice can be initialized:
//
// es := NewLineSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es LineSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.Line, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Line.
// It returns the newly added Line.
func (es LineSlice) AppendEmpty() Line {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewLine())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es LineSlice) MoveAndAppendTo(dest LineSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es LineSlice) RemoveIf(f func(Line) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteLine((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es LineSlice) CopyTo(dest LineSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyLinePtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the Line elements within LineSlice given the
// provided less function so that two instances of LineSlice
// can be compared.
func (es LineSlice) Sort(less func(a, b Line) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// Link represents a pointer from a profile Sample to a trace Span.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewLink function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Link struct {
orig *internal.Link
state *internal.State
}
func newLink(orig *internal.Link, state *internal.State) Link {
return Link{orig: orig, state: state}
}
// NewLink creates a new empty Link.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewLink() Link {
return newLink(internal.NewLink(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Link) MoveTo(dest Link) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteLink(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// TraceID returns the traceid associated with this Link.
func (ms Link) TraceID() pcommon.TraceID {
return pcommon.TraceID(ms.orig.TraceId)
}
// SetTraceID replaces the traceid associated with this Link.
func (ms Link) SetTraceID(v pcommon.TraceID) {
ms.state.AssertMutable()
ms.orig.TraceId = internal.TraceID(v)
}
// SpanID returns the spanid associated with this Link.
func (ms Link) SpanID() pcommon.SpanID {
return pcommon.SpanID(ms.orig.SpanId)
}
// SetSpanID replaces the spanid associated with this Link.
func (ms Link) SetSpanID(v pcommon.SpanID) {
ms.state.AssertMutable()
ms.orig.SpanId = internal.SpanID(v)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Link) CopyTo(dest Link) {
dest.state.AssertMutable()
internal.CopyLink(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// LinkSlice logically represents a slice of Link.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewLinkSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type LinkSlice struct {
orig *[]*internal.Link
state *internal.State
}
func newLinkSlice(orig *[]*internal.Link, state *internal.State) LinkSlice {
return LinkSlice{orig: orig, state: state}
}
// NewLinkSlice creates a LinkSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewLinkSlice() LinkSlice {
orig := []*internal.Link(nil)
return newLinkSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewLinkSlice()".
func (es LinkSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es LinkSlice) At(i int) Link {
return newLink((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es LinkSlice) All() iter.Seq2[int, Link] {
return func(yield func(int, Link) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new LinkSlice can be initialized:
//
// es := NewLinkSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es LinkSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.Link, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Link.
// It returns the newly added Link.
func (es LinkSlice) AppendEmpty() Link {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewLink())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es LinkSlice) MoveAndAppendTo(dest LinkSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es LinkSlice) RemoveIf(f func(Link) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteLink((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es LinkSlice) CopyTo(dest LinkSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyLinkPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the Link elements within LinkSlice given the
// provided less function so that two instances of LinkSlice
// can be compared.
func (es LinkSlice) Sort(less func(a, b Link) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// Location describes function and line table debug information.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewLocation function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Location struct {
orig *internal.Location
state *internal.State
}
func newLocation(orig *internal.Location, state *internal.State) Location {
return Location{orig: orig, state: state}
}
// NewLocation creates a new empty Location.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewLocation() Location {
return newLocation(internal.NewLocation(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Location) MoveTo(dest Location) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteLocation(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// MappingIndex returns the mappingindex associated with this Location.
func (ms Location) MappingIndex() int32 {
return ms.orig.MappingIndex
}
// SetMappingIndex replaces the mappingindex associated with this Location.
func (ms Location) SetMappingIndex(v int32) {
ms.state.AssertMutable()
ms.orig.MappingIndex = v
}
// Address returns the address associated with this Location.
func (ms Location) Address() uint64 {
return ms.orig.Address
}
// SetAddress replaces the address associated with this Location.
func (ms Location) SetAddress(v uint64) {
ms.state.AssertMutable()
ms.orig.Address = v
}
// Lines returns the Lines associated with this Location.
func (ms Location) Lines() LineSlice {
return newLineSlice(&ms.orig.Lines, ms.state)
}
// AttributeIndices returns the AttributeIndices associated with this Location.
func (ms Location) AttributeIndices() pcommon.Int32Slice {
return pcommon.Int32Slice(internal.NewInt32SliceWrapper(&ms.orig.AttributeIndices, ms.state))
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Location) CopyTo(dest Location) {
dest.state.AssertMutable()
internal.CopyLocation(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// LocationSlice logically represents a slice of Location.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewLocationSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type LocationSlice struct {
orig *[]*internal.Location
state *internal.State
}
func newLocationSlice(orig *[]*internal.Location, state *internal.State) LocationSlice {
return LocationSlice{orig: orig, state: state}
}
// NewLocationSlice creates a LocationSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewLocationSlice() LocationSlice {
orig := []*internal.Location(nil)
return newLocationSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewLocationSlice()".
func (es LocationSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es LocationSlice) At(i int) Location {
return newLocation((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es LocationSlice) All() iter.Seq2[int, Location] {
return func(yield func(int, Location) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new LocationSlice can be initialized:
//
// es := NewLocationSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es LocationSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.Location, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Location.
// It returns the newly added Location.
func (es LocationSlice) AppendEmpty() Location {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewLocation())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es LocationSlice) MoveAndAppendTo(dest LocationSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es LocationSlice) RemoveIf(f func(Location) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteLocation((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es LocationSlice) CopyTo(dest LocationSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyLocationPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the Location elements within LocationSlice given the
// provided less function so that two instances of LocationSlice
// can be compared.
func (es LocationSlice) Sort(less func(a, b Location) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// Mapping describes the mapping of a binary in memory, including its address range, file offset, and metadata like build ID
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewMapping function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Mapping struct {
orig *internal.Mapping
state *internal.State
}
func newMapping(orig *internal.Mapping, state *internal.State) Mapping {
return Mapping{orig: orig, state: state}
}
// NewMapping creates a new empty Mapping.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewMapping() Mapping {
return newMapping(internal.NewMapping(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Mapping) MoveTo(dest Mapping) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteMapping(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// MemoryStart returns the memorystart associated with this Mapping.
func (ms Mapping) MemoryStart() uint64 {
return ms.orig.MemoryStart
}
// SetMemoryStart replaces the memorystart associated with this Mapping.
func (ms Mapping) SetMemoryStart(v uint64) {
ms.state.AssertMutable()
ms.orig.MemoryStart = v
}
// MemoryLimit returns the memorylimit associated with this Mapping.
func (ms Mapping) MemoryLimit() uint64 {
return ms.orig.MemoryLimit
}
// SetMemoryLimit replaces the memorylimit associated with this Mapping.
func (ms Mapping) SetMemoryLimit(v uint64) {
ms.state.AssertMutable()
ms.orig.MemoryLimit = v
}
// FileOffset returns the fileoffset associated with this Mapping.
func (ms Mapping) FileOffset() uint64 {
return ms.orig.FileOffset
}
// SetFileOffset replaces the fileoffset associated with this Mapping.
func (ms Mapping) SetFileOffset(v uint64) {
ms.state.AssertMutable()
ms.orig.FileOffset = v
}
// FilenameStrindex returns the filenamestrindex associated with this Mapping.
func (ms Mapping) FilenameStrindex() int32 {
return ms.orig.FilenameStrindex
}
// SetFilenameStrindex replaces the filenamestrindex associated with this Mapping.
func (ms Mapping) SetFilenameStrindex(v int32) {
ms.state.AssertMutable()
ms.orig.FilenameStrindex = v
}
// AttributeIndices returns the AttributeIndices associated with this Mapping.
func (ms Mapping) AttributeIndices() pcommon.Int32Slice {
return pcommon.Int32Slice(internal.NewInt32SliceWrapper(&ms.orig.AttributeIndices, ms.state))
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Mapping) CopyTo(dest Mapping) {
dest.state.AssertMutable()
internal.CopyMapping(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// MappingSlice logically represents a slice of Mapping.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewMappingSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type MappingSlice struct {
orig *[]*internal.Mapping
state *internal.State
}
func newMappingSlice(orig *[]*internal.Mapping, state *internal.State) MappingSlice {
return MappingSlice{orig: orig, state: state}
}
// NewMappingSlice creates a MappingSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewMappingSlice() MappingSlice {
orig := []*internal.Mapping(nil)
return newMappingSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewMappingSlice()".
func (es MappingSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es MappingSlice) At(i int) Mapping {
return newMapping((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es MappingSlice) All() iter.Seq2[int, Mapping] {
return func(yield func(int, Mapping) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new MappingSlice can be initialized:
//
// es := NewMappingSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es MappingSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.Mapping, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Mapping.
// It returns the newly added Mapping.
func (es MappingSlice) AppendEmpty() Mapping {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewMapping())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es MappingSlice) MoveAndAppendTo(dest MappingSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es MappingSlice) RemoveIf(f func(Mapping) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteMapping((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es MappingSlice) CopyTo(dest MappingSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyMappingPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the Mapping elements within MappingSlice given the
// provided less function so that two instances of MappingSlice
// can be compared.
func (es MappingSlice) Sort(less func(a, b Mapping) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// Profile are an implementation of the pprofextended data model.
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewProfile function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Profile struct {
orig *internal.Profile
state *internal.State
}
func newProfile(orig *internal.Profile, state *internal.State) Profile {
return Profile{orig: orig, state: state}
}
// NewProfile creates a new empty Profile.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewProfile() Profile {
return newProfile(internal.NewProfile(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Profile) MoveTo(dest Profile) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteProfile(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// SampleType returns the sampletype associated with this Profile.
func (ms Profile) SampleType() ValueType {
return newValueType(&ms.orig.SampleType, ms.state)
}
// Samples returns the Samples associated with this Profile.
func (ms Profile) Samples() SampleSlice {
return newSampleSlice(&ms.orig.Samples, ms.state)
}
// Time returns the time associated with this Profile.
func (ms Profile) Time() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.TimeUnixNano)
}
// SetTime replaces the time associated with this Profile.
func (ms Profile) SetTime(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.TimeUnixNano = uint64(v)
}
// DurationNano returns the durationnano associated with this Profile.
func (ms Profile) DurationNano() uint64 {
return ms.orig.DurationNano
}
// SetDurationNano replaces the durationnano associated with this Profile.
func (ms Profile) SetDurationNano(v uint64) {
ms.state.AssertMutable()
ms.orig.DurationNano = v
}
// PeriodType returns the periodtype associated with this Profile.
func (ms Profile) PeriodType() ValueType {
return newValueType(&ms.orig.PeriodType, ms.state)
}
// Period returns the period associated with this Profile.
func (ms Profile) Period() int64 {
return ms.orig.Period
}
// SetPeriod replaces the period associated with this Profile.
func (ms Profile) SetPeriod(v int64) {
ms.state.AssertMutable()
ms.orig.Period = v
}
// ProfileID returns the profileid associated with this Profile.
func (ms Profile) ProfileID() ProfileID {
return ProfileID(ms.orig.ProfileId)
}
// SetProfileID replaces the profileid associated with this Profile.
func (ms Profile) SetProfileID(v ProfileID) {
ms.state.AssertMutable()
ms.orig.ProfileId = internal.ProfileID(v)
}
// DroppedAttributesCount returns the droppedattributescount associated with this Profile.
func (ms Profile) DroppedAttributesCount() uint32 {
return ms.orig.DroppedAttributesCount
}
// SetDroppedAttributesCount replaces the droppedattributescount associated with this Profile.
func (ms Profile) SetDroppedAttributesCount(v uint32) {
ms.state.AssertMutable()
ms.orig.DroppedAttributesCount = v
}
// OriginalPayloadFormat returns the originalpayloadformat associated with this Profile.
func (ms Profile) OriginalPayloadFormat() string {
return ms.orig.OriginalPayloadFormat
}
// SetOriginalPayloadFormat replaces the originalpayloadformat associated with this Profile.
func (ms Profile) SetOriginalPayloadFormat(v string) {
ms.state.AssertMutable()
ms.orig.OriginalPayloadFormat = v
}
// OriginalPayload returns the OriginalPayload associated with this Profile.
func (ms Profile) OriginalPayload() pcommon.ByteSlice {
return pcommon.ByteSlice(internal.NewByteSliceWrapper(&ms.orig.OriginalPayload, ms.state))
}
// AttributeIndices returns the AttributeIndices associated with this Profile.
func (ms Profile) AttributeIndices() pcommon.Int32Slice {
return pcommon.Int32Slice(internal.NewInt32SliceWrapper(&ms.orig.AttributeIndices, ms.state))
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Profile) CopyTo(dest Profile) {
dest.state.AssertMutable()
internal.CopyProfile(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Profiles is the top-level struct that is propagated through the profiles pipeline.
// Use NewProfiles to create new instance, zero-initialized instance is not valid for use.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewProfiles function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Profiles internal.ProfilesWrapper
func newProfiles(orig *internal.ExportProfilesServiceRequest, state *internal.State) Profiles {
return Profiles(internal.NewProfilesWrapper(orig, state))
}
// NewProfiles creates a new empty Profiles.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewProfiles() Profiles {
return newProfiles(internal.NewExportProfilesServiceRequest(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Profiles) MoveTo(dest Profiles) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
internal.DeleteExportProfilesServiceRequest(dest.getOrig(), false)
*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()
}
// ResourceProfiles returns the ResourceProfiles associated with this Profiles.
func (ms Profiles) ResourceProfiles() ResourceProfilesSlice {
return newResourceProfilesSlice(&ms.getOrig().ResourceProfiles, ms.getState())
}
// Dictionary returns the dictionary associated with this Profiles.
func (ms Profiles) Dictionary() ProfilesDictionary {
return newProfilesDictionary(&ms.getOrig().Dictionary, ms.getState())
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Profiles) CopyTo(dest Profiles) {
dest.getState().AssertMutable()
internal.CopyExportProfilesServiceRequest(dest.getOrig(), ms.getOrig())
}
func (ms Profiles) getOrig() *internal.ExportProfilesServiceRequest {
return internal.GetProfilesOrig(internal.ProfilesWrapper(ms))
}
func (ms Profiles) getState() *internal.State {
return internal.GetProfilesState(internal.ProfilesWrapper(ms))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ProfilesData represents the profiles data that can be stored in persistent storage,
// OR can be embedded by other protocols that transfer OTLP profiles data but do not
// implement the OTLP protocol.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewProfilesData function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ProfilesData internal.ProfilesDataWrapper
func newProfilesData(orig *internal.ProfilesData, state *internal.State) ProfilesData {
return ProfilesData(internal.NewProfilesDataWrapper(orig, state))
}
// NewProfilesData creates a new empty ProfilesData.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewProfilesData() ProfilesData {
return newProfilesData(internal.NewProfilesData(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ProfilesData) MoveTo(dest ProfilesData) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
internal.DeleteProfilesData(dest.getOrig(), false)
*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()
}
// ResourceProfiles returns the ResourceProfiles associated with this ProfilesData.
func (ms ProfilesData) ResourceProfiles() ResourceProfilesSlice {
return newResourceProfilesSlice(&ms.getOrig().ResourceProfiles, ms.getState())
}
// Dictionary returns the dictionary associated with this ProfilesData.
func (ms ProfilesData) Dictionary() ProfilesDictionary {
return newProfilesDictionary(&ms.getOrig().Dictionary, ms.getState())
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ProfilesData) CopyTo(dest ProfilesData) {
dest.getState().AssertMutable()
internal.CopyProfilesData(dest.getOrig(), ms.getOrig())
}
func (ms ProfilesData) getOrig() *internal.ProfilesData {
return internal.GetProfilesDataOrig(internal.ProfilesDataWrapper(ms))
}
func (ms ProfilesData) getState() *internal.State {
return internal.GetProfilesDataState(internal.ProfilesDataWrapper(ms))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ProfilesDictionary is the reference table containing all data shared by profiles across the message being sent.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewProfilesDictionary function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ProfilesDictionary struct {
orig *internal.ProfilesDictionary
state *internal.State
}
func newProfilesDictionary(orig *internal.ProfilesDictionary, state *internal.State) ProfilesDictionary {
return ProfilesDictionary{orig: orig, state: state}
}
// NewProfilesDictionary creates a new empty ProfilesDictionary.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewProfilesDictionary() ProfilesDictionary {
return newProfilesDictionary(internal.NewProfilesDictionary(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ProfilesDictionary) MoveTo(dest ProfilesDictionary) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteProfilesDictionary(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// MappingTable returns the MappingTable associated with this ProfilesDictionary.
func (ms ProfilesDictionary) MappingTable() MappingSlice {
return newMappingSlice(&ms.orig.MappingTable, ms.state)
}
// LocationTable returns the LocationTable associated with this ProfilesDictionary.
func (ms ProfilesDictionary) LocationTable() LocationSlice {
return newLocationSlice(&ms.orig.LocationTable, ms.state)
}
// FunctionTable returns the FunctionTable associated with this ProfilesDictionary.
func (ms ProfilesDictionary) FunctionTable() FunctionSlice {
return newFunctionSlice(&ms.orig.FunctionTable, ms.state)
}
// LinkTable returns the LinkTable associated with this ProfilesDictionary.
func (ms ProfilesDictionary) LinkTable() LinkSlice {
return newLinkSlice(&ms.orig.LinkTable, ms.state)
}
// StringTable returns the StringTable associated with this ProfilesDictionary.
func (ms ProfilesDictionary) StringTable() pcommon.StringSlice {
return pcommon.StringSlice(internal.NewStringSliceWrapper(&ms.orig.StringTable, ms.state))
}
// AttributeTable returns the AttributeTable associated with this ProfilesDictionary.
func (ms ProfilesDictionary) AttributeTable() KeyValueAndUnitSlice {
return newKeyValueAndUnitSlice(&ms.orig.AttributeTable, ms.state)
}
// StackTable returns the StackTable associated with this ProfilesDictionary.
func (ms ProfilesDictionary) StackTable() StackSlice {
return newStackSlice(&ms.orig.StackTable, ms.state)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ProfilesDictionary) CopyTo(dest ProfilesDictionary) {
dest.state.AssertMutable()
internal.CopyProfilesDictionary(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ProfilesSlice logically represents a slice of Profile.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewProfilesSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ProfilesSlice struct {
orig *[]*internal.Profile
state *internal.State
}
func newProfilesSlice(orig *[]*internal.Profile, state *internal.State) ProfilesSlice {
return ProfilesSlice{orig: orig, state: state}
}
// NewProfilesSlice creates a ProfilesSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewProfilesSlice() ProfilesSlice {
orig := []*internal.Profile(nil)
return newProfilesSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewProfilesSlice()".
func (es ProfilesSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ProfilesSlice) At(i int) Profile {
return newProfile((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ProfilesSlice) All() iter.Seq2[int, Profile] {
return func(yield func(int, Profile) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ProfilesSlice can be initialized:
//
// es := NewProfilesSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ProfilesSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.Profile, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Profile.
// It returns the newly added Profile.
func (es ProfilesSlice) AppendEmpty() Profile {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewProfile())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ProfilesSlice) MoveAndAppendTo(dest ProfilesSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ProfilesSlice) RemoveIf(f func(Profile) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteProfile((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ProfilesSlice) CopyTo(dest ProfilesSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyProfilePtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the Profile elements within ProfilesSlice given the
// provided less function so that two instances of ProfilesSlice
// can be compared.
func (es ProfilesSlice) Sort(less func(a, b Profile) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ResourceProfiles is a collection of profiles from a Resource.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewResourceProfiles function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ResourceProfiles struct {
orig *internal.ResourceProfiles
state *internal.State
}
func newResourceProfiles(orig *internal.ResourceProfiles, state *internal.State) ResourceProfiles {
return ResourceProfiles{orig: orig, state: state}
}
// NewResourceProfiles creates a new empty ResourceProfiles.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewResourceProfiles() ResourceProfiles {
return newResourceProfiles(internal.NewResourceProfiles(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ResourceProfiles) MoveTo(dest ResourceProfiles) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteResourceProfiles(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Resource returns the resource associated with this ResourceProfiles.
func (ms ResourceProfiles) Resource() pcommon.Resource {
return pcommon.Resource(internal.NewResourceWrapper(&ms.orig.Resource, ms.state))
}
// ScopeProfiles returns the ScopeProfiles associated with this ResourceProfiles.
func (ms ResourceProfiles) ScopeProfiles() ScopeProfilesSlice {
return newScopeProfilesSlice(&ms.orig.ScopeProfiles, ms.state)
}
// SchemaUrl returns the schemaurl associated with this ResourceProfiles.
func (ms ResourceProfiles) SchemaUrl() string {
return ms.orig.SchemaUrl
}
// SetSchemaUrl replaces the schemaurl associated with this ResourceProfiles.
func (ms ResourceProfiles) SetSchemaUrl(v string) {
ms.state.AssertMutable()
ms.orig.SchemaUrl = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ResourceProfiles) CopyTo(dest ResourceProfiles) {
dest.state.AssertMutable()
internal.CopyResourceProfiles(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ResourceProfilesSlice logically represents a slice of ResourceProfiles.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewResourceProfilesSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ResourceProfilesSlice struct {
orig *[]*internal.ResourceProfiles
state *internal.State
}
func newResourceProfilesSlice(orig *[]*internal.ResourceProfiles, state *internal.State) ResourceProfilesSlice {
return ResourceProfilesSlice{orig: orig, state: state}
}
// NewResourceProfilesSlice creates a ResourceProfilesSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewResourceProfilesSlice() ResourceProfilesSlice {
orig := []*internal.ResourceProfiles(nil)
return newResourceProfilesSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewResourceProfilesSlice()".
func (es ResourceProfilesSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ResourceProfilesSlice) At(i int) ResourceProfiles {
return newResourceProfiles((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ResourceProfilesSlice) All() iter.Seq2[int, ResourceProfiles] {
return func(yield func(int, ResourceProfiles) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ResourceProfilesSlice can be initialized:
//
// es := NewResourceProfilesSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ResourceProfilesSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.ResourceProfiles, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty ResourceProfiles.
// It returns the newly added ResourceProfiles.
func (es ResourceProfilesSlice) AppendEmpty() ResourceProfiles {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewResourceProfiles())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ResourceProfilesSlice) MoveAndAppendTo(dest ResourceProfilesSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ResourceProfilesSlice) RemoveIf(f func(ResourceProfiles) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteResourceProfiles((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ResourceProfilesSlice) CopyTo(dest ResourceProfilesSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyResourceProfilesPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the ResourceProfiles elements within ResourceProfilesSlice given the
// provided less function so that two instances of ResourceProfilesSlice
// can be compared.
func (es ResourceProfilesSlice) Sort(less func(a, b ResourceProfiles) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// Sample represents each record value encountered within a profiled program.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewSample function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Sample struct {
orig *internal.Sample
state *internal.State
}
func newSample(orig *internal.Sample, state *internal.State) Sample {
return Sample{orig: orig, state: state}
}
// NewSample creates a new empty Sample.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewSample() Sample {
return newSample(internal.NewSample(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Sample) MoveTo(dest Sample) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteSample(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// StackIndex returns the stackindex associated with this Sample.
func (ms Sample) StackIndex() int32 {
return ms.orig.StackIndex
}
// SetStackIndex replaces the stackindex associated with this Sample.
func (ms Sample) SetStackIndex(v int32) {
ms.state.AssertMutable()
ms.orig.StackIndex = v
}
// AttributeIndices returns the AttributeIndices associated with this Sample.
func (ms Sample) AttributeIndices() pcommon.Int32Slice {
return pcommon.Int32Slice(internal.NewInt32SliceWrapper(&ms.orig.AttributeIndices, ms.state))
}
// LinkIndex returns the linkindex associated with this Sample.
func (ms Sample) LinkIndex() int32 {
return ms.orig.LinkIndex
}
// SetLinkIndex replaces the linkindex associated with this Sample.
func (ms Sample) SetLinkIndex(v int32) {
ms.state.AssertMutable()
ms.orig.LinkIndex = v
}
// Values returns the Values associated with this Sample.
func (ms Sample) Values() pcommon.Int64Slice {
return pcommon.Int64Slice(internal.NewInt64SliceWrapper(&ms.orig.Values, ms.state))
}
// TimestampsUnixNano returns the TimestampsUnixNano associated with this Sample.
func (ms Sample) TimestampsUnixNano() pcommon.UInt64Slice {
return pcommon.UInt64Slice(internal.NewUInt64SliceWrapper(&ms.orig.TimestampsUnixNano, ms.state))
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Sample) CopyTo(dest Sample) {
dest.state.AssertMutable()
internal.CopySample(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// SampleSlice logically represents a slice of Sample.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewSampleSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type SampleSlice struct {
orig *[]*internal.Sample
state *internal.State
}
func newSampleSlice(orig *[]*internal.Sample, state *internal.State) SampleSlice {
return SampleSlice{orig: orig, state: state}
}
// NewSampleSlice creates a SampleSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewSampleSlice() SampleSlice {
orig := []*internal.Sample(nil)
return newSampleSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewSampleSlice()".
func (es SampleSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es SampleSlice) At(i int) Sample {
return newSample((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es SampleSlice) All() iter.Seq2[int, Sample] {
return func(yield func(int, Sample) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new SampleSlice can be initialized:
//
// es := NewSampleSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es SampleSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.Sample, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Sample.
// It returns the newly added Sample.
func (es SampleSlice) AppendEmpty() Sample {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewSample())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es SampleSlice) MoveAndAppendTo(dest SampleSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es SampleSlice) RemoveIf(f func(Sample) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteSample((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es SampleSlice) CopyTo(dest SampleSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopySamplePtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the Sample elements within SampleSlice given the
// provided less function so that two instances of SampleSlice
// can be compared.
func (es SampleSlice) Sort(less func(a, b Sample) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ScopeProfiles is a collection of profiles from a LibraryInstrumentation.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewScopeProfiles function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ScopeProfiles struct {
orig *internal.ScopeProfiles
state *internal.State
}
func newScopeProfiles(orig *internal.ScopeProfiles, state *internal.State) ScopeProfiles {
return ScopeProfiles{orig: orig, state: state}
}
// NewScopeProfiles creates a new empty ScopeProfiles.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewScopeProfiles() ScopeProfiles {
return newScopeProfiles(internal.NewScopeProfiles(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ScopeProfiles) MoveTo(dest ScopeProfiles) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteScopeProfiles(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Scope returns the scope associated with this ScopeProfiles.
func (ms ScopeProfiles) Scope() pcommon.InstrumentationScope {
return pcommon.InstrumentationScope(internal.NewInstrumentationScopeWrapper(&ms.orig.Scope, ms.state))
}
// Profiles returns the Profiles associated with this ScopeProfiles.
func (ms ScopeProfiles) Profiles() ProfilesSlice {
return newProfilesSlice(&ms.orig.Profiles, ms.state)
}
// SchemaUrl returns the schemaurl associated with this ScopeProfiles.
func (ms ScopeProfiles) SchemaUrl() string {
return ms.orig.SchemaUrl
}
// SetSchemaUrl replaces the schemaurl associated with this ScopeProfiles.
func (ms ScopeProfiles) SetSchemaUrl(v string) {
ms.state.AssertMutable()
ms.orig.SchemaUrl = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ScopeProfiles) CopyTo(dest ScopeProfiles) {
dest.state.AssertMutable()
internal.CopyScopeProfiles(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ScopeProfilesSlice logically represents a slice of ScopeProfiles.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewScopeProfilesSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ScopeProfilesSlice struct {
orig *[]*internal.ScopeProfiles
state *internal.State
}
func newScopeProfilesSlice(orig *[]*internal.ScopeProfiles, state *internal.State) ScopeProfilesSlice {
return ScopeProfilesSlice{orig: orig, state: state}
}
// NewScopeProfilesSlice creates a ScopeProfilesSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewScopeProfilesSlice() ScopeProfilesSlice {
orig := []*internal.ScopeProfiles(nil)
return newScopeProfilesSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewScopeProfilesSlice()".
func (es ScopeProfilesSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ScopeProfilesSlice) At(i int) ScopeProfiles {
return newScopeProfiles((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ScopeProfilesSlice) All() iter.Seq2[int, ScopeProfiles] {
return func(yield func(int, ScopeProfiles) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ScopeProfilesSlice can be initialized:
//
// es := NewScopeProfilesSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ScopeProfilesSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.ScopeProfiles, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty ScopeProfiles.
// It returns the newly added ScopeProfiles.
func (es ScopeProfilesSlice) AppendEmpty() ScopeProfiles {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewScopeProfiles())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ScopeProfilesSlice) MoveAndAppendTo(dest ScopeProfilesSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ScopeProfilesSlice) RemoveIf(f func(ScopeProfiles) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteScopeProfiles((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ScopeProfilesSlice) CopyTo(dest ScopeProfilesSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyScopeProfilesPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the ScopeProfiles elements within ScopeProfilesSlice given the
// provided less function so that two instances of ScopeProfilesSlice
// can be compared.
func (es ScopeProfilesSlice) Sort(less func(a, b ScopeProfiles) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// Stack represents a stack trace as a list of locations.
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewStack function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Stack struct {
orig *internal.Stack
state *internal.State
}
func newStack(orig *internal.Stack, state *internal.State) Stack {
return Stack{orig: orig, state: state}
}
// NewStack creates a new empty Stack.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewStack() Stack {
return newStack(internal.NewStack(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Stack) MoveTo(dest Stack) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteStack(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// LocationIndices returns the LocationIndices associated with this Stack.
func (ms Stack) LocationIndices() pcommon.Int32Slice {
return pcommon.Int32Slice(internal.NewInt32SliceWrapper(&ms.orig.LocationIndices, ms.state))
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Stack) CopyTo(dest Stack) {
dest.state.AssertMutable()
internal.CopyStack(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// StackSlice logically represents a slice of Stack.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewStackSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type StackSlice struct {
orig *[]*internal.Stack
state *internal.State
}
func newStackSlice(orig *[]*internal.Stack, state *internal.State) StackSlice {
return StackSlice{orig: orig, state: state}
}
// NewStackSlice creates a StackSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewStackSlice() StackSlice {
orig := []*internal.Stack(nil)
return newStackSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewStackSlice()".
func (es StackSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es StackSlice) At(i int) Stack {
return newStack((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es StackSlice) All() iter.Seq2[int, Stack] {
return func(yield func(int, Stack) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new StackSlice can be initialized:
//
// es := NewStackSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es StackSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.Stack, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Stack.
// It returns the newly added Stack.
func (es StackSlice) AppendEmpty() Stack {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewStack())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es StackSlice) MoveAndAppendTo(dest StackSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es StackSlice) RemoveIf(f func(Stack) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteStack((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es StackSlice) CopyTo(dest StackSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyStackPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the Stack elements within StackSlice given the
// provided less function so that two instances of StackSlice
// can be compared.
func (es StackSlice) Sort(less func(a, b Stack) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ValueType describes the type and units of a value.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewValueType function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ValueType struct {
orig *internal.ValueType
state *internal.State
}
func newValueType(orig *internal.ValueType, state *internal.State) ValueType {
return ValueType{orig: orig, state: state}
}
// NewValueType creates a new empty ValueType.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewValueType() ValueType {
return newValueType(internal.NewValueType(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ValueType) MoveTo(dest ValueType) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteValueType(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// TypeStrindex returns the typestrindex associated with this ValueType.
func (ms ValueType) TypeStrindex() int32 {
return ms.orig.TypeStrindex
}
// SetTypeStrindex replaces the typestrindex associated with this ValueType.
func (ms ValueType) SetTypeStrindex(v int32) {
ms.state.AssertMutable()
ms.orig.TypeStrindex = v
}
// UnitStrindex returns the unitstrindex associated with this ValueType.
func (ms ValueType) UnitStrindex() int32 {
return ms.orig.UnitStrindex
}
// SetUnitStrindex replaces the unitstrindex associated with this ValueType.
func (ms ValueType) SetUnitStrindex(v int32) {
ms.state.AssertMutable()
ms.orig.UnitStrindex = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ValueType) CopyTo(dest ValueType) {
dest.state.AssertMutable()
internal.CopyValueType(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofile
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ValueTypeSlice logically represents a slice of ValueType.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewValueTypeSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ValueTypeSlice struct {
orig *[]*internal.ValueType
state *internal.State
}
func newValueTypeSlice(orig *[]*internal.ValueType, state *internal.State) ValueTypeSlice {
return ValueTypeSlice{orig: orig, state: state}
}
// NewValueTypeSlice creates a ValueTypeSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewValueTypeSlice() ValueTypeSlice {
orig := []*internal.ValueType(nil)
return newValueTypeSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewValueTypeSlice()".
func (es ValueTypeSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ValueTypeSlice) At(i int) ValueType {
return newValueType((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ValueTypeSlice) All() iter.Seq2[int, ValueType] {
return func(yield func(int, ValueType) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ValueTypeSlice can be initialized:
//
// es := NewValueTypeSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ValueTypeSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.ValueType, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty ValueType.
// It returns the newly added ValueType.
func (es ValueTypeSlice) AppendEmpty() ValueType {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewValueType())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ValueTypeSlice) MoveAndAppendTo(dest ValueTypeSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ValueTypeSlice) RemoveIf(f func(ValueType) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteValueType((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ValueTypeSlice) CopyTo(dest ValueTypeSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyValueTypePtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the ValueType elements within ValueTypeSlice given the
// provided less function so that two instances of ValueTypeSlice
// can be compared.
func (es ValueTypeSlice) Sort(less func(a, b ValueType) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/otlp"
)
// JSONMarshaler marshals pprofile.Profiles to JSON bytes using the OTLP/JSON format.
type JSONMarshaler struct{}
// MarshalProfiles marshals Profiles to OTLP/JSON format bytes.
// If the input data is read-only, it will be copied to a mutable
// instance before mutation.
func (*JSONMarshaler) MarshalProfiles(pd Profiles) ([]byte, error) {
// Only copy if data is shared/read-only to avoid unnecessary allocation
pdToUse := pd
if pd.IsReadOnly() {
pdCopy := NewProfiles()
pd.CopyTo(pdCopy)
pdToUse = pdCopy
}
// Convert strings to references for efficient transmission
if err := convertProfilesToReferences(pdToUse); err != nil {
return nil, err
}
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
pdToUse.getOrig().MarshalJSON(dest)
if dest.Error() != nil {
return nil, dest.Error()
}
return slices.Clone(dest.Buffer()), nil
}
// JSONUnmarshaler unmarshals OTLP/JSON formatted-bytes to pprofile.Profiles.
type JSONUnmarshaler struct {
// DisallowUnknownFields causes UnmarshalProfiles to return an error when the
// input contains JSON object fields that are not defined by the OTLP
// schema. When false (the default), unknown fields are silently ignored.
//
// Warning: enabling this option breaks forwards compatibility with future
// evolutions of the OTLP format, as fields added to the format in newer
// versions will be rejected as unknown.
DisallowUnknownFields bool
// prevent unkeyed literal initialization
_ struct{}
}
// UnmarshalProfiles from OTLP/JSON format into pprofile.Profiles.
func (u *JSONUnmarshaler) UnmarshalProfiles(buf []byte) (Profiles, error) {
iter := json.BorrowIterator(buf)
defer json.ReturnIterator(iter)
iter.SetDisallowUnknownFields(u.DisallowUnknownFields)
pd := NewProfiles()
pd.getOrig().UnmarshalJSON(iter)
if iter.Error() != nil {
return Profiles{}, iter.Error()
}
otlp.MigrateProfiles(pd.getOrig().ResourceProfiles)
// Resolve all string_value_ref and key_ref to their actual strings
// so the pdata API works transparently
if err := resolveProfilesReferences(pd); err != nil {
return Profiles{}, err
}
return pd, nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "fmt"
// Equal checks equality with another KeyValueAndUnit
// It assumes both structs refer to the same dictionary.
func (ms KeyValueAndUnit) Equal(val KeyValueAndUnit) bool {
return ms.KeyStrindex() == val.KeyStrindex() &&
ms.UnitStrindex() == val.UnitStrindex() &&
ms.Value().Equal(val.Value())
}
// switchDictionary updates the KeyValueAndUnit, switching its indices from one
// dictionary to another.
func (ms KeyValueAndUnit) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
if ms.KeyStrindex() > 0 {
if src.StringTable().Len() <= int(ms.KeyStrindex()) {
return fmt.Errorf("invalid key index %d", ms.KeyStrindex())
}
idx, err := mi.setString(dst.StringTable(), src.StringTable().At(int(ms.KeyStrindex())))
if err != nil {
return fmt.Errorf("couldn't set key: %w", err)
}
ms.SetKeyStrindex(idx)
}
if ms.UnitStrindex() > 0 {
if src.StringTable().Len() <= int(ms.UnitStrindex()) {
return fmt.Errorf("invalid unit index %d", ms.UnitStrindex())
}
idx, err := mi.setString(dst.StringTable(), src.StringTable().At(int(ms.UnitStrindex())))
if err != nil {
return fmt.Errorf("couldn't set unit: %w", err)
}
ms.SetUnitStrindex(idx)
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "fmt"
// Equal checks equality with another LineSlice
func (l LineSlice) Equal(val LineSlice) bool {
if l.Len() != val.Len() {
return false
}
for i := range l.Len() {
if !l.At(i).Equal(val.At(i)) {
return false
}
}
return true
}
// Equal checks equality with another Line
func (l Line) Equal(val Line) bool {
return l.Column() == val.Column() &&
l.FunctionIndex() == val.FunctionIndex() &&
l.Line() == val.Line()
}
// switchDictionary updates the Line, switching its indices from one
// dictionary to another.
func (l Line) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
if l.FunctionIndex() > 0 {
if src.FunctionTable().Len() <= int(l.FunctionIndex()) {
return fmt.Errorf("invalid function index %d", l.FunctionIndex())
}
fn := src.FunctionTable().At(int(l.FunctionIndex()))
idx, err := mi.setFunction(dst.FunctionTable(), fn)
if err != nil {
return fmt.Errorf("couldn't set function: %w", err)
}
l.SetFunctionIndex(idx)
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
// Equal checks equality with another Link
func (ms Link) Equal(val Link) bool {
return ms.TraceID() == val.TraceID() &&
ms.SpanID() == val.SpanID()
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"errors"
"math"
)
var errTooManyLinkTableEntries = errors.New("too many entries in LinkTable")
// SetLink updates a LinkTable, adding or providing a value and returns its
// index.
func SetLink(table LinkSlice, li Link) (int32, error) {
for j, l := range table.All() {
if l.Equal(li) {
if j > math.MaxInt32 {
return 0, errTooManyLinkTableEntries
}
return int32(j), nil
}
}
if table.Len() >= math.MaxInt32 {
return 0, errTooManyLinkTableEntries
}
li.CopyTo(table.AppendEmpty())
return int32(table.Len() - 1), nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "fmt"
// Equal checks equality with another Location
func (ms Location) Equal(val Location) bool {
return ms.MappingIndex() == val.MappingIndex() &&
ms.Address() == val.Address() &&
ms.AttributeIndices().Equal(val.AttributeIndices()) &&
ms.Lines().Equal(val.Lines())
}
// switchDictionary updates the Location, switching its indices from one
// dictionary to another.
func (ms Location) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
if ms.MappingIndex() > 0 {
if src.MappingTable().Len() <= int(ms.MappingIndex()) {
return fmt.Errorf("invalid mapping index %d", ms.MappingIndex())
}
mapping := src.MappingTable().At(int(ms.MappingIndex()))
idx, err := mi.setMapping(dst.MappingTable(), mapping)
if err != nil {
return fmt.Errorf("couldn't set mapping: %w", err)
}
ms.SetMappingIndex(idx)
}
for i, v := range ms.AttributeIndices().All() {
if v < 0 || src.AttributeTable().Len() <= int(v) {
return fmt.Errorf("invalid attribute index %d", v)
}
attr := src.AttributeTable().At(int(v))
idx, err := mi.setAttribute(dst.AttributeTable(), attr)
if err != nil {
return fmt.Errorf("couldn't set attribute %d: %w", i, err)
}
ms.AttributeIndices().SetAt(i, idx)
}
for i, v := range ms.Lines().All() {
if err := v.switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("couldn't switch dictionary for line %d: %w", i, err)
}
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"errors"
"fmt"
"math"
)
// FromLocationIndices builds a slice containing all the locations of a Stack.
// Updates made to the returned map will not be applied back to the Stack.
func FromLocationIndices(table LocationSlice, record Stack) (LocationSlice, error) {
m := NewLocationSlice()
m.EnsureCapacity(record.LocationIndices().Len())
for _, idx := range record.LocationIndices().All() {
if idx < 0 || int(idx) >= table.Len() {
return m, fmt.Errorf("location index %d out of bounds [0, %d)", idx, table.Len())
}
l := table.At(int(idx))
l.CopyTo(m.AppendEmpty())
}
return m, nil
}
var errTooManyLocationTableEntries = errors.New("too many entries in LocationTable")
// SetLocation updates a LocationTable, adding or providing a value and returns
// its index.
func SetLocation(table LocationSlice, loc Location) (int32, error) {
for j, a := range table.All() {
if a.Equal(loc) {
if j > math.MaxInt32 {
return 0, errTooManyLocationTableEntries
}
return int32(j), nil
}
}
if table.Len() >= math.MaxInt32 {
return 0, errTooManyLocationTableEntries
}
loc.CopyTo(table.AppendEmpty())
return int32(table.Len() - 1), nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "fmt"
// Equal checks equality with another Mapping
func (ms Mapping) Equal(val Mapping) bool {
return ms.MemoryStart() == val.MemoryStart() &&
ms.MemoryLimit() == val.MemoryLimit() &&
ms.FileOffset() == val.FileOffset() &&
ms.FilenameStrindex() == val.FilenameStrindex() &&
ms.AttributeIndices().Equal(val.AttributeIndices())
}
// switchDictionary updates the Mapping, switching its indices from one
// dictionary to another.
func (ms Mapping) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
if ms.FilenameStrindex() > 0 {
if src.StringTable().Len() <= int(ms.FilenameStrindex()) {
return fmt.Errorf("invalid filename index %d", ms.FilenameStrindex())
}
idx, err := mi.setString(dst.StringTable(), src.StringTable().At(int(ms.FilenameStrindex())))
if err != nil {
return fmt.Errorf("couldn't set filename: %w", err)
}
ms.SetFilenameStrindex(idx)
}
for i, v := range ms.AttributeIndices().All() {
if v < 0 || src.AttributeTable().Len() <= int(v) {
return fmt.Errorf("invalid attribute index %d", v)
}
attr := src.AttributeTable().At(int(v))
idx, err := mi.setAttribute(dst.AttributeTable(), attr)
if err != nil {
return fmt.Errorf("couldn't set attribute %d: %w", i, err)
}
ms.AttributeIndices().SetAt(i, idx)
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"errors"
"math"
)
var errTooManyMappingTableEntries = errors.New("too many entries in MappingTable")
// SetMapping updates a MappingTable, adding or providing a value and returns
// its index.
func SetMapping(table MappingSlice, ma Mapping) (int32, error) {
for j, m := range table.All() {
if m.Equal(ma) {
if j > math.MaxInt32 {
return 0, errTooManyMappingTableEntries
}
return int32(j), nil
}
}
if table.Len() >= math.MaxInt32 {
return 0, errTooManyMappingTableEntries
}
ma.CopyTo(table.AppendEmpty())
return int32(table.Len() - 1), nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "go.opentelemetry.io/collector/pdata/internal/otlp"
var _ MarshalSizer = (*ProtoMarshaler)(nil)
type ProtoMarshaler struct{}
// MarshalProfiles marshals Profiles to gRPC format bytes.
// If the input data is read-only, it will be copied to a mutable
// instance before mutation.
func (e *ProtoMarshaler) MarshalProfiles(pd Profiles) ([]byte, error) {
// Only copy if data is shared/read-only to avoid unnecessary allocation
pdToUse := pd
if pd.IsReadOnly() {
pdCopy := NewProfiles()
pd.CopyTo(pdCopy)
pdToUse = pdCopy
}
// Convert strings to references for efficient transmission
if err := convertProfilesToReferences(pdToUse); err != nil {
return nil, err
}
size := pdToUse.getOrig().SizeProto()
buf := make([]byte, size)
_ = pdToUse.getOrig().MarshalProto(buf)
return buf, nil
}
func (e *ProtoMarshaler) ProfilesSize(pd Profiles) int {
return pd.getOrig().SizeProto()
}
func (e *ProtoMarshaler) ResourceProfilesSize(pd ResourceProfiles) int {
return pd.orig.SizeProto()
}
func (e *ProtoMarshaler) ScopeProfilesSize(pd ScopeProfiles) int {
return pd.orig.SizeProto()
}
func (e *ProtoMarshaler) ProfileSize(pd Profile) int {
return pd.orig.SizeProto()
}
type ProtoUnmarshaler struct{}
func (d *ProtoUnmarshaler) UnmarshalProfiles(buf []byte) (Profiles, error) {
pd := NewProfiles()
err := pd.getOrig().UnmarshalProto(buf)
if err != nil {
return Profiles{}, err
}
otlp.MigrateProfiles(pd.getOrig().ResourceProfiles)
// Resolve all string_value_ref and key_ref to their actual strings
// so the pdata API works transparently
if err := resolveProfilesReferences(pd); err != nil {
return Profiles{}, err
}
return pd, nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofileotlp
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ExportPartialSuccess represents the details of a partially successful export request.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExportPartialSuccess function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExportPartialSuccess struct {
orig *internal.ExportProfilesPartialSuccess
state *internal.State
}
func newExportPartialSuccess(orig *internal.ExportProfilesPartialSuccess, state *internal.State) ExportPartialSuccess {
return ExportPartialSuccess{orig: orig, state: state}
}
// NewExportPartialSuccess creates a new empty ExportPartialSuccess.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExportPartialSuccess() ExportPartialSuccess {
return newExportPartialSuccess(internal.NewExportProfilesPartialSuccess(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExportPartialSuccess) MoveTo(dest ExportPartialSuccess) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExportProfilesPartialSuccess(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// RejectedProfiles returns the rejectedprofiles associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) RejectedProfiles() int64 {
return ms.orig.RejectedProfiles
}
// SetRejectedProfiles replaces the rejectedprofiles associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) SetRejectedProfiles(v int64) {
ms.state.AssertMutable()
ms.orig.RejectedProfiles = v
}
// ErrorMessage returns the errormessage associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) ErrorMessage() string {
return ms.orig.ErrorMessage
}
// SetErrorMessage replaces the errormessage associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) SetErrorMessage(v string) {
ms.state.AssertMutable()
ms.orig.ErrorMessage = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExportPartialSuccess) CopyTo(dest ExportPartialSuccess) {
dest.state.AssertMutable()
internal.CopyExportProfilesPartialSuccess(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package pprofileotlp
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ExportResponse represents the response for gRPC/HTTP client/server.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExportResponse function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExportResponse struct {
orig *internal.ExportProfilesServiceResponse
state *internal.State
}
func newExportResponse(orig *internal.ExportProfilesServiceResponse, state *internal.State) ExportResponse {
return ExportResponse{orig: orig, state: state}
}
// NewExportResponse creates a new empty ExportResponse.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExportResponse() ExportResponse {
return newExportResponse(internal.NewExportProfilesServiceResponse(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExportResponse) MoveTo(dest ExportResponse) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExportProfilesServiceResponse(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// PartialSuccess returns the partialsuccess associated with this ExportResponse.
func (ms ExportResponse) PartialSuccess() ExportPartialSuccess {
return newExportPartialSuccess(&ms.orig.PartialSuccess, ms.state)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExportResponse) CopyTo(dest ExportResponse) {
dest.state.AssertMutable()
internal.CopyExportProfilesServiceResponse(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofileotlp // import "go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp"
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/internal/otelgrpc"
"go.opentelemetry.io/collector/pdata/internal/otlp"
"go.opentelemetry.io/collector/pdata/pprofile"
)
// GRPCClient is the client API for OTLP-GRPC Profiles service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type GRPCClient interface {
// Export pprofile.Profiles to the server.
//
// For performance reasons, it is recommended to keep this RPC
// alive for the entire life of the application.
Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error)
// unexported disallow implementation of the GRPCClient.
unexported()
}
// NewGRPCClient returns a new GRPCClient connected using the given connection.
func NewGRPCClient(cc *grpc.ClientConn) GRPCClient {
return &grpcClient{rawClient: otelgrpc.NewProfilesServiceClient(cc)}
}
type grpcClient struct {
rawClient otelgrpc.ProfilesServiceClient
}
// Export implements the Client interface.
func (c *grpcClient) Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error) {
// Dictionary conversion mutates the request. Always copy it because even
// mutable pdata may be shared with other non-mutating consumers.
profilesCopy := pprofile.NewProfiles()
request.Profiles().CopyTo(profilesCopy)
request = NewExportRequestFromProfiles(profilesCopy)
if err := otlp.ConvertProfilesToReferences(request.orig); err != nil {
return ExportResponse{}, err
}
// FromOutgoingContext returns a copy. Replace any supplied version rather
// than appending: the metadata must identify the schema we actually encode.
md, _ := metadata.FromOutgoingContext(ctx)
if md == nil {
md = metadata.MD{}
}
md.Set(DevelopmentVersionHeader, DevelopmentVersion)
ctx = metadata.NewOutgoingContext(ctx, md)
rsp, err := c.rawClient.Export(ctx, request.orig, opts...)
if err != nil {
return ExportResponse{}, err
}
return ExportResponse{orig: rsp, state: internal.NewState()}, err
}
func (c *grpcClient) unexported() {}
// GRPCServer is the server API for OTLP gRPC ProfilesService service.
// Implementations MUST embed UnimplementedGRPCServer.
type GRPCServer interface {
// Export is called every time a new request is received.
//
// For performance reasons, it is recommended to keep this RPC
// alive for the entire life of the application.
Export(context.Context, ExportRequest) (ExportResponse, error)
// unexported disallow implementation of the GRPCServer.
unexported()
}
var _ GRPCServer = (*UnimplementedGRPCServer)(nil)
// UnimplementedGRPCServer MUST be embedded to have forward compatible implementations.
type UnimplementedGRPCServer struct{}
func (*UnimplementedGRPCServer) Export(context.Context, ExportRequest) (ExportResponse, error) {
return ExportResponse{}, status.Errorf(codes.Unimplemented, "method Export not implemented")
}
func (*UnimplementedGRPCServer) unexported() {}
// RegisterGRPCServer registers the GRPCServer to the grpc.Server.
func RegisterGRPCServer(s *grpc.Server, srv GRPCServer) {
otelgrpc.RegisterProfilesServiceServer(s, &rawProfilesServer{srv: srv})
}
type rawProfilesServer struct {
srv GRPCServer
}
func (s rawProfilesServer) Export(ctx context.Context, request *internal.ExportProfilesServiceRequest) (*internal.ExportProfilesServiceResponse, error) {
otlp.MigrateProfiles(request.ResourceProfiles)
if err := otlp.ResolveProfilesReferences(request); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
rsp, err := s.srv.Export(ctx, ExportRequest{orig: request, state: internal.NewState()})
return rsp.orig, err
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofileotlp // import "go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp"
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pprofile"
)
// ExportRequest represents the request for gRPC/HTTP client/server.
// It's a wrapper for pprofile.Profiles data.
type ExportRequest struct {
orig *internal.ExportProfilesServiceRequest
state *internal.State
}
// NewExportRequest returns an empty ExportRequest.
func NewExportRequest() ExportRequest {
return ExportRequest{
orig: &internal.ExportProfilesServiceRequest{},
state: internal.NewState(),
}
}
// NewExportRequestFromProfiles returns a ExportRequest from pprofile.Profiles.
// Because ExportRequest is a wrapper for pprofile.Profiles,
// any changes to the provided Profiles struct will be reflected in the ExportRequest and vice versa.
func NewExportRequestFromProfiles(td pprofile.Profiles) ExportRequest {
return ExportRequest{
orig: internal.GetProfilesOrig(internal.ProfilesWrapper(td)),
state: internal.GetProfilesState(internal.ProfilesWrapper(td)),
}
}
// MarshalProto marshals ExportRequest into proto bytes.
// Delegates to pprofile.ProtoMarshaler so attribute strings are referenced via
// the ProfilesDictionary string table.
func (ms ExportRequest) MarshalProto() ([]byte, error) {
return (&pprofile.ProtoMarshaler{}).MarshalProfiles(ms.Profiles())
}
// UnmarshalProto unmarshalls ExportRequest from proto bytes.
// Delegates to pprofile.ProtoUnmarshaler so string-table references are resolved.
func (ms ExportRequest) UnmarshalProto(data []byte) error {
pd, err := (&pprofile.ProtoUnmarshaler{}).UnmarshalProfiles(data)
if err != nil {
return err
}
pd.MoveTo(ms.Profiles())
return nil
}
// MarshalJSON marshals ExportRequest into JSON bytes.
func (ms ExportRequest) MarshalJSON() ([]byte, error) {
return (&pprofile.JSONMarshaler{}).MarshalProfiles(ms.Profiles())
}
// UnmarshalJSON unmarshalls ExportRequest from JSON bytes.
func (ms ExportRequest) UnmarshalJSON(data []byte) error {
pd, err := (&pprofile.JSONUnmarshaler{}).UnmarshalProfiles(data)
if err != nil {
return err
}
pd.MoveTo(ms.Profiles())
return nil
}
func (ms ExportRequest) Profiles() pprofile.Profiles {
return pprofile.Profiles(internal.NewProfilesWrapper(ms.orig, ms.state))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofileotlp // import "go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal/json"
)
// MarshalProto marshals ExportResponse into proto bytes.
func (ms ExportResponse) MarshalProto() ([]byte, error) {
size := ms.orig.SizeProto()
buf := make([]byte, size)
_ = ms.orig.MarshalProto(buf)
return buf, nil
}
// UnmarshalProto unmarshalls ExportResponse from proto bytes.
func (ms ExportResponse) UnmarshalProto(data []byte) error {
return ms.orig.UnmarshalProto(data)
}
// MarshalJSON marshals ExportResponse into JSON bytes.
func (ms ExportResponse) MarshalJSON() ([]byte, error) {
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
ms.orig.MarshalJSON(dest)
return slices.Clone(dest.Buffer()), dest.Error()
}
// UnmarshalJSON unmarshalls ExportResponse from JSON bytes.
func (ms ExportResponse) UnmarshalJSON(data []byte) error {
iter := json.BorrowIterator(data)
defer json.ReturnIterator(iter)
ms.orig.UnmarshalJSON(iter)
return iter.Error()
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofileotlp // import "go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp"
import "go.opentelemetry.io/collector/pdata/internal/otlp"
// DevelopmentVersion is the OTLP Profiles development version encoded and decoded
// by this package. It is determined by the compiled-in schema, not configuration.
const DevelopmentVersion = otlp.ProfilesDevelopmentVersion
// DevelopmentVersionHeader is the request metadata key for the OTLP Profiles
// development version. HTTP header names are case-insensitive.
const DevelopmentVersionHeader = otlp.ProfilesDevelopmentVersionHeader
// ValidateDevelopmentVersion validates all values of the Profiles development
// version request metadata. It must be called before deserializing the payload.
// Absent metadata identifies version 1. Malformed, repeated, and unsupported
// values are rejected. The gRPC server performs this validation automatically.
func ValidateDevelopmentVersion(values []string) error {
return otlp.ValidateProfilesDevelopmentVersion(values)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"fmt"
)
// switchDictionary updates the Profile, switching its indices from one
// dictionary to another.
func (ms Profile) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
for i, v := range ms.AttributeIndices().All() {
if v < 0 || src.AttributeTable().Len() <= int(v) {
return fmt.Errorf("invalid attribute index %d", v)
}
attr := src.AttributeTable().At(int(v))
idx, err := mi.setAttribute(dst.AttributeTable(), attr)
if err != nil {
return fmt.Errorf("couldn't set attribute %d: %w", i, err)
}
ms.AttributeIndices().SetAt(i, idx)
}
for i, v := range ms.Samples().All() {
if err := v.switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("error switching dictionary for sample %d: %w", i, err)
}
}
if err := ms.PeriodType().switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("error switching dictionary for period type: %w", err)
}
if err := ms.SampleType().switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("error switching dictionary for sample type: %w", err)
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"encoding/hex"
"go.opentelemetry.io/collector/pdata/internal"
)
var emptyProfileID = ProfileID([16]byte{})
// ProfileID is a profile identifier.
type ProfileID [16]byte
// NewProfileIDEmpty returns a new empty (all zero bytes) ProfileID.
func NewProfileIDEmpty() ProfileID {
return emptyProfileID
}
// String returns string representation of the ProfileID.
//
// Important: Don't rely on this method to get a string identifier of ProfileID.
// Use hex.EncodeToString explicitly instead.
// This method is meant to implement Stringer interface for display purposes only.
func (ms ProfileID) String() string {
if ms.IsEmpty() {
return ""
}
return hex.EncodeToString(ms[:])
}
// IsEmpty returns true if id doesn't contain at least one non-zero byte.
func (ms ProfileID) IsEmpty() bool {
return internal.ProfileID(ms).IsEmpty()
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "fmt"
// MarkReadOnly marks the ResourceProfiles as shared so that no further modifications can be done on it.
func (ms Profiles) MarkReadOnly() {
ms.getState().MarkReadOnly()
}
// IsReadOnly returns true if this ResourceProfiles instance is read-only.
func (ms Profiles) IsReadOnly() bool {
return ms.getState().IsReadOnly()
}
// SampleCount calculates the total number of samples.
func (ms Profiles) SampleCount() int {
sampleCount := 0
rps := ms.ResourceProfiles()
for i := 0; i < rps.Len(); i++ {
rp := rps.At(i)
sps := rp.ScopeProfiles()
for j := 0; j < sps.Len(); j++ {
pcs := sps.At(j).Profiles()
for k := 0; k < pcs.Len(); k++ {
sampleCount += pcs.At(k).Samples().Len()
}
}
}
return sampleCount
}
// switchDictionary updates the Profiles, switching its indices from one
// dictionary to another.
func (ms Profiles) switchDictionary(src, dst ProfilesDictionary) error {
mi := newMergeIndex(dst)
for i, v := range ms.Dictionary().AttributeTable().All() {
if err := v.switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("couldn't switch attribute %d: %w", i, err)
}
}
for i, v := range ms.Dictionary().FunctionTable().All() {
if err := v.switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("couldn't switch function %d: %w", i, err)
}
}
for i, v := range ms.Dictionary().MappingTable().All() {
if err := v.switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("couldn't switch mapping %d: %w", i, err)
}
}
for i, v := range ms.Dictionary().LocationTable().All() {
if err := v.switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("couldn't switch location %d: %w", i, err)
}
}
for i, v := range ms.Dictionary().StackTable().All() {
if err := v.switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("couldn't switch stack %d: %w", i, err)
}
}
for i, v := range ms.ResourceProfiles().All() {
if err := v.switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("error switching dictionary for resource profile %d: %w", i, err)
}
}
return nil
}
// ProfileCount calculates the total number of profile records.
func (ms Profiles) ProfileCount() int {
profileCount := 0
rps := ms.ResourceProfiles()
for i := 0; i < rps.Len(); i++ {
rp := rps.At(i)
sps := rp.ScopeProfiles()
for j := 0; j < sps.Len(); j++ {
profileCount += sps.At(j).Profiles().Len()
}
}
return profileCount
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
// MergeTo merges the current Profiles into dest, updating the destination
// dictionary as needed and appending the resource profiles.
// The source Profiles is consumed and marked read-only after this operation.
func (ms Profiles) MergeTo(dest Profiles) error {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
if ms.getOrig() == dest.getOrig() {
return nil
}
if err := ms.switchDictionary(ms.Dictionary(), dest.Dictionary()); err != nil {
return err
}
ms.ResourceProfiles().MoveAndAppendTo(dest.ResourceProfiles())
ms.MarkReadOnly()
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "fmt"
// switchDictionary updates the ResourceProfiles, switching its indices from one
// dictionary to another.
func (ms ResourceProfiles) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
for i, v := range ms.ScopeProfiles().All() {
if err := v.switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("error switching dictionary for scope profile %d: %w", i, err)
}
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "fmt"
// switchDictionary updates the Sample, switching its indices from one
// dictionary to another.
func (ms Sample) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
for i, v := range ms.AttributeIndices().All() {
if v < 0 || src.AttributeTable().Len() <= int(v) {
return fmt.Errorf("invalid attribute index %d", v)
}
attr := src.AttributeTable().At(int(v))
idx, err := mi.setAttribute(dst.AttributeTable(), attr)
if err != nil {
return fmt.Errorf("couldn't set attribute %d: %w", i, err)
}
ms.AttributeIndices().SetAt(i, idx)
}
if ms.LinkIndex() > 0 {
if src.LinkTable().Len() <= int(ms.LinkIndex()) {
return fmt.Errorf("invalid link index %d", ms.LinkIndex())
}
idx, err := mi.setLink(dst.LinkTable(), src.LinkTable().At(int(ms.LinkIndex())))
if err != nil {
return fmt.Errorf("couldn't set link: %w", err)
}
ms.SetLinkIndex(idx)
}
if ms.StackIndex() > 0 {
if src.StackTable().Len() <= int(ms.StackIndex()) {
return fmt.Errorf("invalid stack index %d", ms.StackIndex())
}
stack := src.StackTable().At(int(ms.StackIndex()))
idx, err := mi.setStack(dst.StackTable(), stack)
if err != nil {
return fmt.Errorf("couldn't set stack: %w", err)
}
ms.SetStackIndex(idx)
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "fmt"
// switchDictionary updates the ScopeProfiles, switching its indices from one
// dictionary to another.
func (ms ScopeProfiles) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
for i, v := range ms.Profiles().All() {
if err := v.switchDictionary(src, dst, mi); err != nil {
return fmt.Errorf("error switching dictionary for profile %d: %w", i, err)
}
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"fmt"
)
// Equal checks equality with another Stack
func (ms Stack) Equal(val Stack) bool {
if ms.LocationIndices().Len() != val.LocationIndices().Len() {
return false
}
for i := range ms.LocationIndices().Len() {
if ms.LocationIndices().At(i) != val.LocationIndices().At(i) {
return false
}
}
return true
}
// switchDictionary updates the Stack, switching its indices from one
// dictionary to another.
func (ms Stack) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
for i, v := range ms.LocationIndices().All() {
if v < 0 || src.LocationTable().Len() <= int(v) {
return fmt.Errorf("invalid location index %d", v)
}
loc := src.LocationTable().At(int(v))
idx, err := mi.setLocation(dst.LocationTable(), loc)
if err != nil {
return fmt.Errorf("couldn't set location %d: %w", i, err)
}
ms.LocationIndices().SetAt(i, idx)
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"errors"
"math"
)
var errTooManyStackTableEntries = errors.New("too many entries in StackTable")
// SetStack updates a StackSlice, adding or providing a stack and returns its
// index.
func SetStack(table StackSlice, st Stack) (int32, error) {
for j, l := range table.All() {
if l.Equal(st) {
if j > math.MaxInt32 {
return 0, errTooManyStackTableEntries
}
return int32(j), nil
}
}
if table.Len() >= math.MaxInt32 {
return 0, errTooManyStackTableEntries
}
st.CopyTo(table.AppendEmpty())
return int32(table.Len() - 1), nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import (
"errors"
"math"
"go.opentelemetry.io/collector/pdata/pcommon"
)
var errTooManyStringTableEntries = errors.New("too many entries in StringTable")
// SetString updates a StringTable, adding or providing a value and returns its index.
func SetString(table pcommon.StringSlice, val string) (int32, error) {
for j, v := range table.All() {
if v == val {
if j > math.MaxInt32 {
return 0, errTooManyStringTableEntries
}
// Return the index of the existing value.
return int32(j), nil
}
}
if table.Len() >= math.MaxInt32 {
return 0, errTooManyStringTableEntries
}
table.Append(val)
return int32(table.Len() - 1), nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile"
import "fmt"
// switchDictionary updates the ValueType, switching its indices from one
// dictionary to another.
func (ms ValueType) switchDictionary(src, dst ProfilesDictionary, mi *mergeIndex) error {
if ms.TypeStrindex() > 0 {
if src.StringTable().Len() <= int(ms.TypeStrindex()) {
return fmt.Errorf("invalid type index %d", ms.TypeStrindex())
}
idx, err := mi.setString(dst.StringTable(), src.StringTable().At(int(ms.TypeStrindex())))
if err != nil {
return fmt.Errorf("couldn't set type: %w", err)
}
ms.SetTypeStrindex(idx)
}
if ms.UnitStrindex() > 0 {
if src.StringTable().Len() <= int(ms.UnitStrindex()) {
return fmt.Errorf("invalid unit index %d", ms.UnitStrindex())
}
idx, err := mi.setString(dst.StringTable(), src.StringTable().At(int(ms.UnitStrindex())))
if err != nil {
return fmt.Errorf("couldn't set unit: %w", err)
}
ms.SetUnitStrindex(idx)
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ResourceSpans is a collection of spans from a Resource.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewResourceSpans function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ResourceSpans struct {
orig *internal.ResourceSpans
state *internal.State
}
func newResourceSpans(orig *internal.ResourceSpans, state *internal.State) ResourceSpans {
return ResourceSpans{orig: orig, state: state}
}
// NewResourceSpans creates a new empty ResourceSpans.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewResourceSpans() ResourceSpans {
return newResourceSpans(internal.NewResourceSpans(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ResourceSpans) MoveTo(dest ResourceSpans) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteResourceSpans(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Resource returns the resource associated with this ResourceSpans.
func (ms ResourceSpans) Resource() pcommon.Resource {
return pcommon.Resource(internal.NewResourceWrapper(&ms.orig.Resource, ms.state))
}
// ScopeSpans returns the ScopeSpans associated with this ResourceSpans.
func (ms ResourceSpans) ScopeSpans() ScopeSpansSlice {
return newScopeSpansSlice(&ms.orig.ScopeSpans, ms.state)
}
// SchemaUrl returns the schemaurl associated with this ResourceSpans.
func (ms ResourceSpans) SchemaUrl() string {
return ms.orig.SchemaUrl
}
// SetSchemaUrl replaces the schemaurl associated with this ResourceSpans.
func (ms ResourceSpans) SetSchemaUrl(v string) {
ms.state.AssertMutable()
ms.orig.SchemaUrl = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ResourceSpans) CopyTo(dest ResourceSpans) {
dest.state.AssertMutable()
internal.CopyResourceSpans(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ResourceSpansSlice logically represents a slice of ResourceSpans.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewResourceSpansSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ResourceSpansSlice struct {
orig *[]*internal.ResourceSpans
state *internal.State
}
func newResourceSpansSlice(orig *[]*internal.ResourceSpans, state *internal.State) ResourceSpansSlice {
return ResourceSpansSlice{orig: orig, state: state}
}
// NewResourceSpansSlice creates a ResourceSpansSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewResourceSpansSlice() ResourceSpansSlice {
orig := []*internal.ResourceSpans(nil)
return newResourceSpansSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewResourceSpansSlice()".
func (es ResourceSpansSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ResourceSpansSlice) At(i int) ResourceSpans {
return newResourceSpans((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ResourceSpansSlice) All() iter.Seq2[int, ResourceSpans] {
return func(yield func(int, ResourceSpans) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ResourceSpansSlice can be initialized:
//
// es := NewResourceSpansSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ResourceSpansSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.ResourceSpans, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty ResourceSpans.
// It returns the newly added ResourceSpans.
func (es ResourceSpansSlice) AppendEmpty() ResourceSpans {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewResourceSpans())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ResourceSpansSlice) MoveAndAppendTo(dest ResourceSpansSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ResourceSpansSlice) RemoveIf(f func(ResourceSpans) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteResourceSpans((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ResourceSpansSlice) CopyTo(dest ResourceSpansSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyResourceSpansPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the ResourceSpans elements within ResourceSpansSlice given the
// provided less function so that two instances of ResourceSpansSlice
// can be compared.
func (es ResourceSpansSlice) Sort(less func(a, b ResourceSpans) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// ScopeSpans is a collection of spans from a LibraryInstrumentation.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewScopeSpans function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ScopeSpans struct {
orig *internal.ScopeSpans
state *internal.State
}
func newScopeSpans(orig *internal.ScopeSpans, state *internal.State) ScopeSpans {
return ScopeSpans{orig: orig, state: state}
}
// NewScopeSpans creates a new empty ScopeSpans.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewScopeSpans() ScopeSpans {
return newScopeSpans(internal.NewScopeSpans(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ScopeSpans) MoveTo(dest ScopeSpans) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteScopeSpans(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Scope returns the scope associated with this ScopeSpans.
func (ms ScopeSpans) Scope() pcommon.InstrumentationScope {
return pcommon.InstrumentationScope(internal.NewInstrumentationScopeWrapper(&ms.orig.Scope, ms.state))
}
// Spans returns the Spans associated with this ScopeSpans.
func (ms ScopeSpans) Spans() SpanSlice {
return newSpanSlice(&ms.orig.Spans, ms.state)
}
// SchemaUrl returns the schemaurl associated with this ScopeSpans.
func (ms ScopeSpans) SchemaUrl() string {
return ms.orig.SchemaUrl
}
// SetSchemaUrl replaces the schemaurl associated with this ScopeSpans.
func (ms ScopeSpans) SetSchemaUrl(v string) {
ms.state.AssertMutable()
ms.orig.SchemaUrl = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ScopeSpans) CopyTo(dest ScopeSpans) {
dest.state.AssertMutable()
internal.CopyScopeSpans(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// ScopeSpansSlice logically represents a slice of ScopeSpans.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewScopeSpansSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ScopeSpansSlice struct {
orig *[]*internal.ScopeSpans
state *internal.State
}
func newScopeSpansSlice(orig *[]*internal.ScopeSpans, state *internal.State) ScopeSpansSlice {
return ScopeSpansSlice{orig: orig, state: state}
}
// NewScopeSpansSlice creates a ScopeSpansSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewScopeSpansSlice() ScopeSpansSlice {
orig := []*internal.ScopeSpans(nil)
return newScopeSpansSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewScopeSpansSlice()".
func (es ScopeSpansSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es ScopeSpansSlice) At(i int) ScopeSpans {
return newScopeSpans((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es ScopeSpansSlice) All() iter.Seq2[int, ScopeSpans] {
return func(yield func(int, ScopeSpans) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new ScopeSpansSlice can be initialized:
//
// es := NewScopeSpansSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es ScopeSpansSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.ScopeSpans, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty ScopeSpans.
// It returns the newly added ScopeSpans.
func (es ScopeSpansSlice) AppendEmpty() ScopeSpans {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewScopeSpans())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es ScopeSpansSlice) MoveAndAppendTo(dest ScopeSpansSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es ScopeSpansSlice) RemoveIf(f func(ScopeSpans) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteScopeSpans((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es ScopeSpansSlice) CopyTo(dest ScopeSpansSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopyScopeSpansPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the ScopeSpans elements within ScopeSpansSlice given the
// provided less function so that two instances of ScopeSpansSlice
// can be compared.
func (es ScopeSpansSlice) Sort(less func(a, b ScopeSpans) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// Span represents a single operation within a trace.
// See Span definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewSpan function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Span struct {
orig *internal.Span
state *internal.State
}
func newSpan(orig *internal.Span, state *internal.State) Span {
return Span{orig: orig, state: state}
}
// NewSpan creates a new empty Span.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewSpan() Span {
return newSpan(internal.NewSpan(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Span) MoveTo(dest Span) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteSpan(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// TraceID returns the traceid associated with this Span.
func (ms Span) TraceID() pcommon.TraceID {
return pcommon.TraceID(ms.orig.TraceId)
}
// SetTraceID replaces the traceid associated with this Span.
func (ms Span) SetTraceID(v pcommon.TraceID) {
ms.state.AssertMutable()
ms.orig.TraceId = internal.TraceID(v)
}
// SpanID returns the spanid associated with this Span.
func (ms Span) SpanID() pcommon.SpanID {
return pcommon.SpanID(ms.orig.SpanId)
}
// SetSpanID replaces the spanid associated with this Span.
func (ms Span) SetSpanID(v pcommon.SpanID) {
ms.state.AssertMutable()
ms.orig.SpanId = internal.SpanID(v)
}
// TraceState returns the tracestate associated with this Span.
func (ms Span) TraceState() pcommon.TraceState {
return pcommon.TraceState(internal.NewTraceStateWrapper(&ms.orig.TraceState, ms.state))
}
// ParentSpanID returns the parentspanid associated with this Span.
func (ms Span) ParentSpanID() pcommon.SpanID {
return pcommon.SpanID(ms.orig.ParentSpanId)
}
// SetParentSpanID replaces the parentspanid associated with this Span.
func (ms Span) SetParentSpanID(v pcommon.SpanID) {
ms.state.AssertMutable()
ms.orig.ParentSpanId = internal.SpanID(v)
}
// Flags returns the flags associated with this Span.
func (ms Span) Flags() uint32 {
return ms.orig.Flags
}
// SetFlags replaces the flags associated with this Span.
func (ms Span) SetFlags(v uint32) {
ms.state.AssertMutable()
ms.orig.Flags = v
}
// Name returns the name associated with this Span.
func (ms Span) Name() string {
return ms.orig.Name
}
// SetName replaces the name associated with this Span.
func (ms Span) SetName(v string) {
ms.state.AssertMutable()
ms.orig.Name = v
}
// Kind returns the kind associated with this Span.
func (ms Span) Kind() SpanKind {
return SpanKind(ms.orig.Kind)
}
// SetKind replaces the kind associated with this Span.
func (ms Span) SetKind(v SpanKind) {
ms.state.AssertMutable()
ms.orig.Kind = internal.SpanKind(v)
}
// StartTimestamp returns the starttimestamp associated with this Span.
func (ms Span) StartTimestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.StartTimeUnixNano)
}
// SetStartTimestamp replaces the starttimestamp associated with this Span.
func (ms Span) SetStartTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.StartTimeUnixNano = uint64(v)
}
// EndTimestamp returns the endtimestamp associated with this Span.
func (ms Span) EndTimestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.EndTimeUnixNano)
}
// SetEndTimestamp replaces the endtimestamp associated with this Span.
func (ms Span) SetEndTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.EndTimeUnixNano = uint64(v)
}
// Attributes returns the Attributes associated with this Span.
func (ms Span) Attributes() pcommon.Map {
return pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))
}
// DroppedAttributesCount returns the droppedattributescount associated with this Span.
func (ms Span) DroppedAttributesCount() uint32 {
return ms.orig.DroppedAttributesCount
}
// SetDroppedAttributesCount replaces the droppedattributescount associated with this Span.
func (ms Span) SetDroppedAttributesCount(v uint32) {
ms.state.AssertMutable()
ms.orig.DroppedAttributesCount = v
}
// Events returns the Events associated with this Span.
func (ms Span) Events() SpanEventSlice {
return newSpanEventSlice(&ms.orig.Events, ms.state)
}
// DroppedEventsCount returns the droppedeventscount associated with this Span.
func (ms Span) DroppedEventsCount() uint32 {
return ms.orig.DroppedEventsCount
}
// SetDroppedEventsCount replaces the droppedeventscount associated with this Span.
func (ms Span) SetDroppedEventsCount(v uint32) {
ms.state.AssertMutable()
ms.orig.DroppedEventsCount = v
}
// Links returns the Links associated with this Span.
func (ms Span) Links() SpanLinkSlice {
return newSpanLinkSlice(&ms.orig.Links, ms.state)
}
// DroppedLinksCount returns the droppedlinkscount associated with this Span.
func (ms Span) DroppedLinksCount() uint32 {
return ms.orig.DroppedLinksCount
}
// SetDroppedLinksCount replaces the droppedlinkscount associated with this Span.
func (ms Span) SetDroppedLinksCount(v uint32) {
ms.state.AssertMutable()
ms.orig.DroppedLinksCount = v
}
// Status returns the status associated with this Span.
func (ms Span) Status() Status {
return newStatus(&ms.orig.Status, ms.state)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Span) CopyTo(dest Span) {
dest.state.AssertMutable()
internal.CopySpan(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// SpanEvent is a time-stamped annotation of the span, consisting of user-supplied
// text description and key-value pairs. See OTLP for event definition.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewSpanEvent function to create new instances.
// Important: zero-initialized instance is not valid for use.
type SpanEvent struct {
orig *internal.SpanEvent
state *internal.State
}
func newSpanEvent(orig *internal.SpanEvent, state *internal.State) SpanEvent {
return SpanEvent{orig: orig, state: state}
}
// NewSpanEvent creates a new empty SpanEvent.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewSpanEvent() SpanEvent {
return newSpanEvent(internal.NewSpanEvent(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms SpanEvent) MoveTo(dest SpanEvent) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteSpanEvent(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Timestamp returns the timestamp associated with this SpanEvent.
func (ms SpanEvent) Timestamp() pcommon.Timestamp {
return pcommon.Timestamp(ms.orig.TimeUnixNano)
}
// SetTimestamp replaces the timestamp associated with this SpanEvent.
func (ms SpanEvent) SetTimestamp(v pcommon.Timestamp) {
ms.state.AssertMutable()
ms.orig.TimeUnixNano = uint64(v)
}
// Name returns the name associated with this SpanEvent.
func (ms SpanEvent) Name() string {
return ms.orig.Name
}
// SetName replaces the name associated with this SpanEvent.
func (ms SpanEvent) SetName(v string) {
ms.state.AssertMutable()
ms.orig.Name = v
}
// Attributes returns the Attributes associated with this SpanEvent.
func (ms SpanEvent) Attributes() pcommon.Map {
return pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))
}
// DroppedAttributesCount returns the droppedattributescount associated with this SpanEvent.
func (ms SpanEvent) DroppedAttributesCount() uint32 {
return ms.orig.DroppedAttributesCount
}
// SetDroppedAttributesCount replaces the droppedattributescount associated with this SpanEvent.
func (ms SpanEvent) SetDroppedAttributesCount(v uint32) {
ms.state.AssertMutable()
ms.orig.DroppedAttributesCount = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms SpanEvent) CopyTo(dest SpanEvent) {
dest.state.AssertMutable()
internal.CopySpanEvent(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// SpanEventSlice logically represents a slice of SpanEvent.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewSpanEventSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type SpanEventSlice struct {
orig *[]*internal.SpanEvent
state *internal.State
}
func newSpanEventSlice(orig *[]*internal.SpanEvent, state *internal.State) SpanEventSlice {
return SpanEventSlice{orig: orig, state: state}
}
// NewSpanEventSlice creates a SpanEventSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewSpanEventSlice() SpanEventSlice {
orig := []*internal.SpanEvent(nil)
return newSpanEventSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewSpanEventSlice()".
func (es SpanEventSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es SpanEventSlice) At(i int) SpanEvent {
return newSpanEvent((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es SpanEventSlice) All() iter.Seq2[int, SpanEvent] {
return func(yield func(int, SpanEvent) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new SpanEventSlice can be initialized:
//
// es := NewSpanEventSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es SpanEventSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.SpanEvent, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty SpanEvent.
// It returns the newly added SpanEvent.
func (es SpanEventSlice) AppendEmpty() SpanEvent {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewSpanEvent())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es SpanEventSlice) MoveAndAppendTo(dest SpanEventSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es SpanEventSlice) RemoveIf(f func(SpanEvent) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteSpanEvent((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es SpanEventSlice) CopyTo(dest SpanEventSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopySpanEventPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the SpanEvent elements within SpanEventSlice given the
// provided less function so that two instances of SpanEventSlice
// can be compared.
func (es SpanEventSlice) Sort(less func(a, b SpanEvent) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/pcommon"
)
// SpanLink is a pointer from the current span to another span in the same trace or in a
// different trace.
// See Link definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewSpanLink function to create new instances.
// Important: zero-initialized instance is not valid for use.
type SpanLink struct {
orig *internal.SpanLink
state *internal.State
}
func newSpanLink(orig *internal.SpanLink, state *internal.State) SpanLink {
return SpanLink{orig: orig, state: state}
}
// NewSpanLink creates a new empty SpanLink.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewSpanLink() SpanLink {
return newSpanLink(internal.NewSpanLink(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms SpanLink) MoveTo(dest SpanLink) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteSpanLink(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// TraceID returns the traceid associated with this SpanLink.
func (ms SpanLink) TraceID() pcommon.TraceID {
return pcommon.TraceID(ms.orig.TraceId)
}
// SetTraceID replaces the traceid associated with this SpanLink.
func (ms SpanLink) SetTraceID(v pcommon.TraceID) {
ms.state.AssertMutable()
ms.orig.TraceId = internal.TraceID(v)
}
// SpanID returns the spanid associated with this SpanLink.
func (ms SpanLink) SpanID() pcommon.SpanID {
return pcommon.SpanID(ms.orig.SpanId)
}
// SetSpanID replaces the spanid associated with this SpanLink.
func (ms SpanLink) SetSpanID(v pcommon.SpanID) {
ms.state.AssertMutable()
ms.orig.SpanId = internal.SpanID(v)
}
// TraceState returns the tracestate associated with this SpanLink.
func (ms SpanLink) TraceState() pcommon.TraceState {
return pcommon.TraceState(internal.NewTraceStateWrapper(&ms.orig.TraceState, ms.state))
}
// Attributes returns the Attributes associated with this SpanLink.
func (ms SpanLink) Attributes() pcommon.Map {
return pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))
}
// DroppedAttributesCount returns the droppedattributescount associated with this SpanLink.
func (ms SpanLink) DroppedAttributesCount() uint32 {
return ms.orig.DroppedAttributesCount
}
// SetDroppedAttributesCount replaces the droppedattributescount associated with this SpanLink.
func (ms SpanLink) SetDroppedAttributesCount(v uint32) {
ms.state.AssertMutable()
ms.orig.DroppedAttributesCount = v
}
// Flags returns the flags associated with this SpanLink.
func (ms SpanLink) Flags() uint32 {
return ms.orig.Flags
}
// SetFlags replaces the flags associated with this SpanLink.
func (ms SpanLink) SetFlags(v uint32) {
ms.state.AssertMutable()
ms.orig.Flags = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms SpanLink) CopyTo(dest SpanLink) {
dest.state.AssertMutable()
internal.CopySpanLink(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// SpanLinkSlice logically represents a slice of SpanLink.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewSpanLinkSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type SpanLinkSlice struct {
orig *[]*internal.SpanLink
state *internal.State
}
func newSpanLinkSlice(orig *[]*internal.SpanLink, state *internal.State) SpanLinkSlice {
return SpanLinkSlice{orig: orig, state: state}
}
// NewSpanLinkSlice creates a SpanLinkSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewSpanLinkSlice() SpanLinkSlice {
orig := []*internal.SpanLink(nil)
return newSpanLinkSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewSpanLinkSlice()".
func (es SpanLinkSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es SpanLinkSlice) At(i int) SpanLink {
return newSpanLink((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es SpanLinkSlice) All() iter.Seq2[int, SpanLink] {
return func(yield func(int, SpanLink) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new SpanLinkSlice can be initialized:
//
// es := NewSpanLinkSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es SpanLinkSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.SpanLink, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty SpanLink.
// It returns the newly added SpanLink.
func (es SpanLinkSlice) AppendEmpty() SpanLink {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewSpanLink())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es SpanLinkSlice) MoveAndAppendTo(dest SpanLinkSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es SpanLinkSlice) RemoveIf(f func(SpanLink) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteSpanLink((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es SpanLinkSlice) CopyTo(dest SpanLinkSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopySpanLinkPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the SpanLink elements within SpanLinkSlice given the
// provided less function so that two instances of SpanLinkSlice
// can be compared.
func (es SpanLinkSlice) Sort(less func(a, b SpanLink) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"iter"
"sort"
"go.opentelemetry.io/collector/pdata/internal"
)
// SpanSlice logically represents a slice of Span.
//
// This is a reference type. If passed by value and callee modifies it, the
// caller will see the modification.
//
// Must use NewSpanSlice function to create new instances.
// Important: zero-initialized instance is not valid for use.
type SpanSlice struct {
orig *[]*internal.Span
state *internal.State
}
func newSpanSlice(orig *[]*internal.Span, state *internal.State) SpanSlice {
return SpanSlice{orig: orig, state: state}
}
// NewSpanSlice creates a SpanSliceWrapper with 0 elements.
// Can use "EnsureCapacity" to initialize with a given capacity.
func NewSpanSlice() SpanSlice {
orig := []*internal.Span(nil)
return newSpanSlice(&orig, internal.NewState())
}
// Len returns the number of elements in the slice.
//
// Returns "0" for a newly instance created with "NewSpanSlice()".
func (es SpanSlice) Len() int {
return len(*es.orig)
}
// At returns the element at the given index.
//
// This function is used mostly for iterating over all the values in the slice:
//
// for i := 0; i < es.Len(); i++ {
// e := es.At(i)
// ... // Do something with the element
// }
func (es SpanSlice) At(i int) Span {
return newSpan((*es.orig)[i], es.state)
}
// All returns an iterator over index-value pairs in the slice.
//
// for i, v := range es.All() {
// ... // Do something with index-value pair
// }
func (es SpanSlice) All() iter.Seq2[int, Span] {
return func(yield func(int, Span) bool) {
for i := 0; i < es.Len(); i++ {
if !yield(i, es.At(i)) {
return
}
}
}
}
// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.
// 1. If the newCap <= cap then no change in capacity.
// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.
//
// Here is how a new SpanSlice can be initialized:
//
// es := NewSpanSlice()
// es.EnsureCapacity(4)
// for i := 0; i < 4; i++ {
// e := es.AppendEmpty()
// // Here should set all the values for e.
// }
func (es SpanSlice) EnsureCapacity(newCap int) {
es.state.AssertMutable()
oldCap := cap(*es.orig)
if newCap <= oldCap {
return
}
newOrig := make([]*internal.Span, len(*es.orig), newCap)
copy(newOrig, *es.orig)
*es.orig = newOrig
}
// AppendEmpty will append to the end of the slice an empty Span.
// It returns the newly added Span.
func (es SpanSlice) AppendEmpty() Span {
es.state.AssertMutable()
*es.orig = append(*es.orig, internal.NewSpan())
return es.At(es.Len() - 1)
}
// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.
// The current slice will be cleared.
func (es SpanSlice) MoveAndAppendTo(dest SpanSlice) {
es.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if es.orig == dest.orig {
return
}
if *dest.orig == nil {
// We can simply move the entire vector and avoid any allocations.
*dest.orig = *es.orig
} else {
*dest.orig = append(*dest.orig, *es.orig...)
}
*es.orig = nil
}
// RemoveIf calls f sequentially for each element present in the slice.
// If f returns true, the element is removed from the slice.
func (es SpanSlice) RemoveIf(f func(Span) bool) {
es.state.AssertMutable()
newLen := 0
for i := 0; i < len(*es.orig); i++ {
if f(es.At(i)) {
internal.DeleteSpan((*es.orig)[i], true)
(*es.orig)[i] = nil
continue
}
if newLen == i {
// Nothing to move, element is at the right place.
newLen++
continue
}
(*es.orig)[newLen] = (*es.orig)[i]
// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.
(*es.orig)[i] = nil
newLen++
}
*es.orig = (*es.orig)[:newLen]
}
// CopyTo copies all elements from the current slice overriding the destination.
func (es SpanSlice) CopyTo(dest SpanSlice) {
dest.state.AssertMutable()
if es.orig == dest.orig {
return
}
*dest.orig = internal.CopySpanPtrSlice(*dest.orig, *es.orig)
}
// Sort sorts the Span elements within SpanSlice given the
// provided less function so that two instances of SpanSlice
// can be compared.
func (es SpanSlice) Sort(less func(a, b Span) bool) {
es.state.AssertMutable()
sort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Status is an optional final status for this span. Semantically, when Status was not
// set, that means the span ended without errors and to assume Status.Ok (code = 0).
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewStatus function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Status struct {
orig *internal.Status
state *internal.State
}
func newStatus(orig *internal.Status, state *internal.State) Status {
return Status{orig: orig, state: state}
}
// NewStatus creates a new empty Status.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewStatus() Status {
return newStatus(internal.NewStatus(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Status) MoveTo(dest Status) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteStatus(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// Message returns the message associated with this Status.
func (ms Status) Message() string {
return ms.orig.Message
}
// SetMessage replaces the message associated with this Status.
func (ms Status) SetMessage(v string) {
ms.state.AssertMutable()
ms.orig.Message = v
}
// Code returns the code associated with this Status.
func (ms Status) Code() StatusCode {
return StatusCode(ms.orig.Code)
}
// SetCode replaces the code associated with this Status.
func (ms Status) SetCode(v StatusCode) {
ms.state.AssertMutable()
ms.orig.Code = internal.StatusCode(v)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Status) CopyTo(dest Status) {
dest.state.AssertMutable()
internal.CopyStatus(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptrace
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// Traces is the top-level struct that is propagated through the traces pipeline.
// Use NewTraces to create new instance, zero-initialized instance is not valid for use.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewTraces function to create new instances.
// Important: zero-initialized instance is not valid for use.
type Traces internal.TracesWrapper
func newTraces(orig *internal.ExportTraceServiceRequest, state *internal.State) Traces {
return Traces(internal.NewTracesWrapper(orig, state))
}
// NewTraces creates a new empty Traces.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewTraces() Traces {
return newTraces(internal.NewExportTraceServiceRequest(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Traces) MoveTo(dest Traces) {
ms.getState().AssertMutable()
dest.getState().AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.getOrig() == dest.getOrig() {
return
}
internal.DeleteExportTraceServiceRequest(dest.getOrig(), false)
*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()
}
// ResourceSpans returns the ResourceSpans associated with this Traces.
func (ms Traces) ResourceSpans() ResourceSpansSlice {
return newResourceSpansSlice(&ms.getOrig().ResourceSpans, ms.getState())
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms Traces) CopyTo(dest Traces) {
dest.getState().AssertMutable()
internal.CopyExportTraceServiceRequest(dest.getOrig(), ms.getOrig())
}
func (ms Traces) getOrig() *internal.ExportTraceServiceRequest {
return internal.GetTracesOrig(internal.TracesWrapper(ms))
}
func (ms Traces) getState() *internal.State {
return internal.GetTracesState(internal.TracesWrapper(ms))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ptrace // import "go.opentelemetry.io/collector/pdata/ptrace"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/otlp"
)
// JSONMarshaler marshals Traces to JSON bytes using the OTLP/JSON format.
type JSONMarshaler struct{}
// MarshalTraces to the OTLP/JSON format.
func (*JSONMarshaler) MarshalTraces(td Traces) ([]byte, error) {
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
td.getOrig().MarshalJSON(dest)
if dest.Error() != nil {
return nil, dest.Error()
}
return slices.Clone(dest.Buffer()), nil
}
// JSONUnmarshaler unmarshals OTLP/JSON formatted-bytes to Traces.
type JSONUnmarshaler struct {
// prevent unkeyed literal initialization
_ struct{}
// DisallowUnknownFields causes UnmarshalTraces to return an error when the
// input contains JSON object fields that are not defined by the OTLP
// schema. When false (the default), unknown fields are silently ignored.
//
// Warning: enabling this option breaks forwards compatibility with future
// evolutions of the OTLP format, as fields added to the format in newer
// versions will be rejected as unknown.
DisallowUnknownFields bool
}
// UnmarshalTraces from OTLP/JSON format into Traces.
func (u *JSONUnmarshaler) UnmarshalTraces(buf []byte) (Traces, error) {
iter := json.BorrowIterator(buf)
defer json.ReturnIterator(iter)
iter.SetDisallowUnknownFields(u.DisallowUnknownFields)
td := NewTraces()
td.getOrig().UnmarshalJSON(iter)
if iter.Error() != nil {
return Traces{}, iter.Error()
}
otlp.MigrateTraces(td.getOrig().ResourceSpans)
return td, nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ptrace // import "go.opentelemetry.io/collector/pdata/ptrace"
var _ MarshalSizer = (*ProtoMarshaler)(nil)
type ProtoMarshaler struct{}
func (e *ProtoMarshaler) MarshalTraces(td Traces) ([]byte, error) {
size := td.getOrig().SizeProto()
buf := make([]byte, size)
_ = td.getOrig().MarshalProto(buf)
return buf, nil
}
func (e *ProtoMarshaler) TracesSize(td Traces) int {
return td.getOrig().SizeProto()
}
func (e *ProtoMarshaler) ResourceSpansSize(td ResourceSpans) int {
return td.orig.SizeProto()
}
func (e *ProtoMarshaler) ScopeSpansSize(td ScopeSpans) int {
return td.orig.SizeProto()
}
func (e *ProtoMarshaler) SpanSize(td Span) int {
return td.orig.SizeProto()
}
type ProtoUnmarshaler struct{}
func (d *ProtoUnmarshaler) UnmarshalTraces(buf []byte) (Traces, error) {
td := NewTraces()
err := td.getOrig().UnmarshalProto(buf)
if err != nil {
return Traces{}, err
}
return td, nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptraceotlp
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ExportPartialSuccess represents the details of a partially successful export request.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExportPartialSuccess function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExportPartialSuccess struct {
orig *internal.ExportTracePartialSuccess
state *internal.State
}
func newExportPartialSuccess(orig *internal.ExportTracePartialSuccess, state *internal.State) ExportPartialSuccess {
return ExportPartialSuccess{orig: orig, state: state}
}
// NewExportPartialSuccess creates a new empty ExportPartialSuccess.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExportPartialSuccess() ExportPartialSuccess {
return newExportPartialSuccess(internal.NewExportTracePartialSuccess(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExportPartialSuccess) MoveTo(dest ExportPartialSuccess) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExportTracePartialSuccess(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// RejectedSpans returns the rejectedspans associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) RejectedSpans() int64 {
return ms.orig.RejectedSpans
}
// SetRejectedSpans replaces the rejectedspans associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) SetRejectedSpans(v int64) {
ms.state.AssertMutable()
ms.orig.RejectedSpans = v
}
// ErrorMessage returns the errormessage associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) ErrorMessage() string {
return ms.orig.ErrorMessage
}
// SetErrorMessage replaces the errormessage associated with this ExportPartialSuccess.
func (ms ExportPartialSuccess) SetErrorMessage(v string) {
ms.state.AssertMutable()
ms.orig.ErrorMessage = v
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExportPartialSuccess) CopyTo(dest ExportPartialSuccess) {
dest.state.AssertMutable()
internal.CopyExportTracePartialSuccess(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Code generated by "internal/cmd/pdatagen/main.go". DO NOT EDIT.
// To regenerate this file run "make genpdata".
package ptraceotlp
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// ExportResponse represents the response for gRPC/HTTP client/server.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewExportResponse function to create new instances.
// Important: zero-initialized instance is not valid for use.
type ExportResponse struct {
orig *internal.ExportTraceServiceResponse
state *internal.State
}
func newExportResponse(orig *internal.ExportTraceServiceResponse, state *internal.State) ExportResponse {
return ExportResponse{orig: orig, state: state}
}
// NewExportResponse creates a new empty ExportResponse.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewExportResponse() ExportResponse {
return newExportResponse(internal.NewExportTraceServiceResponse(), internal.NewState())
}
// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms ExportResponse) MoveTo(dest ExportResponse) {
ms.state.AssertMutable()
dest.state.AssertMutable()
// If they point to the same data, they are the same, nothing to do.
if ms.orig == dest.orig {
return
}
internal.DeleteExportTraceServiceResponse(dest.orig, false)
*dest.orig, *ms.orig = *ms.orig, *dest.orig
}
// PartialSuccess returns the partialsuccess associated with this ExportResponse.
func (ms ExportResponse) PartialSuccess() ExportPartialSuccess {
return newExportPartialSuccess(&ms.orig.PartialSuccess, ms.state)
}
// CopyTo copies all properties from the current struct overriding the destination.
func (ms ExportResponse) CopyTo(dest ExportResponse) {
dest.state.AssertMutable()
internal.CopyExportTraceServiceResponse(dest.orig, ms.orig)
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ptraceotlp // import "go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/internal/otelgrpc"
"go.opentelemetry.io/collector/pdata/internal/otlp"
)
// GRPCClient is the client API for OTLP-GRPC Traces service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type GRPCClient interface {
// Export ptrace.Traces to the server.
//
// For performance reasons, it is recommended to keep this RPC
// alive for the entire life of the application.
Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error)
// unexported disallow implementation of the GRPCClient.
unexported()
}
// NewGRPCClient returns a new GRPCClient connected using the given connection.
func NewGRPCClient(cc *grpc.ClientConn) GRPCClient {
return &grpcClient{rawClient: otelgrpc.NewTraceServiceClient(cc)}
}
type grpcClient struct {
rawClient otelgrpc.TraceServiceClient
}
// Export implements the Client interface.
func (c *grpcClient) Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error) {
rsp, err := c.rawClient.Export(ctx, request.orig, opts...)
if err != nil {
return ExportResponse{}, err
}
return ExportResponse{orig: rsp, state: internal.NewState()}, err
}
func (c *grpcClient) unexported() {}
// GRPCServer is the server API for OTLP gRPC TracesService service.
// Implementations MUST embed UnimplementedGRPCServer.
type GRPCServer interface {
// Export is called every time a new request is received.
//
// For performance reasons, it is recommended to keep this RPC
// alive for the entire life of the application.
Export(context.Context, ExportRequest) (ExportResponse, error)
// unexported disallow implementation of the GRPCServer.
unexported()
}
var _ GRPCServer = (*UnimplementedGRPCServer)(nil)
// UnimplementedGRPCServer MUST be embedded to have forward compatible implementations.
type UnimplementedGRPCServer struct{}
func (*UnimplementedGRPCServer) Export(context.Context, ExportRequest) (ExportResponse, error) {
return ExportResponse{}, status.Errorf(codes.Unimplemented, "method Export not implemented")
}
func (*UnimplementedGRPCServer) unexported() {}
// RegisterGRPCServer registers the GRPCServer to the grpc.Server.
func RegisterGRPCServer(s *grpc.Server, srv GRPCServer) {
otelgrpc.RegisterTraceServiceServer(s, &rawTracesServer{srv: srv})
}
type rawTracesServer struct {
srv GRPCServer
}
func (s rawTracesServer) Export(ctx context.Context, request *internal.ExportTraceServiceRequest) (*internal.ExportTraceServiceResponse, error) {
otlp.MigrateTraces(request.ResourceSpans)
rsp, err := s.srv.Export(ctx, ExportRequest{orig: request, state: internal.NewState()})
return rsp.orig, err
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ptraceotlp // import "go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal"
"go.opentelemetry.io/collector/pdata/internal/json"
"go.opentelemetry.io/collector/pdata/internal/otlp"
"go.opentelemetry.io/collector/pdata/ptrace"
)
// ExportRequest represents the request for gRPC/HTTP client/server.
// It's a wrapper for ptrace.Traces data.
type ExportRequest struct {
orig *internal.ExportTraceServiceRequest
state *internal.State
}
// NewExportRequest returns an empty ExportRequest.
func NewExportRequest() ExportRequest {
return ExportRequest{
orig: &internal.ExportTraceServiceRequest{},
state: internal.NewState(),
}
}
// NewExportRequestFromTraces returns a ExportRequest from ptrace.Traces.
// Because ExportRequest is a wrapper for ptrace.Traces,
// any changes to the provided Traces struct will be reflected in the ExportRequest and vice versa.
func NewExportRequestFromTraces(td ptrace.Traces) ExportRequest {
return ExportRequest{
orig: internal.GetTracesOrig(internal.TracesWrapper(td)),
state: internal.GetTracesState(internal.TracesWrapper(td)),
}
}
// MarshalProto marshals ExportRequest into proto bytes.
func (ms ExportRequest) MarshalProto() ([]byte, error) {
size := ms.orig.SizeProto()
buf := make([]byte, size)
_ = ms.orig.MarshalProto(buf)
return buf, nil
}
// UnmarshalProto unmarshalls ExportRequest from proto bytes.
func (ms ExportRequest) UnmarshalProto(data []byte) error {
err := ms.orig.UnmarshalProto(data)
if err != nil {
return err
}
otlp.MigrateTraces(ms.orig.ResourceSpans)
return nil
}
// MarshalJSON marshals ExportRequest into JSON bytes.
func (ms ExportRequest) MarshalJSON() ([]byte, error) {
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
ms.orig.MarshalJSON(dest)
if dest.Error() != nil {
return nil, dest.Error()
}
return slices.Clone(dest.Buffer()), nil
}
// UnmarshalJSON unmarshalls ExportRequest from JSON bytes.
func (ms ExportRequest) UnmarshalJSON(data []byte) error {
iter := json.BorrowIterator(data)
defer json.ReturnIterator(iter)
ms.orig.UnmarshalJSON(iter)
return iter.Error()
}
func (ms ExportRequest) Traces() ptrace.Traces {
return ptrace.Traces(internal.NewTracesWrapper(ms.orig, ms.state))
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ptraceotlp // import "go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
import (
"slices"
"go.opentelemetry.io/collector/pdata/internal/json"
)
// MarshalProto marshals ExportResponse into proto bytes.
func (ms ExportResponse) MarshalProto() ([]byte, error) {
size := ms.orig.SizeProto()
buf := make([]byte, size)
_ = ms.orig.MarshalProto(buf)
return buf, nil
}
// UnmarshalProto unmarshalls ExportResponse from proto bytes.
func (ms ExportResponse) UnmarshalProto(data []byte) error {
return ms.orig.UnmarshalProto(data)
}
// MarshalJSON marshals ExportResponse into JSON bytes.
func (ms ExportResponse) MarshalJSON() ([]byte, error) {
dest := json.BorrowStream(nil)
defer json.ReturnStream(dest)
ms.orig.MarshalJSON(dest)
return slices.Clone(dest.Buffer()), dest.Error()
}
// UnmarshalJSON unmarshalls ExportResponse from JSON bytes.
func (ms ExportResponse) UnmarshalJSON(data []byte) error {
iter := json.BorrowIterator(data)
defer json.ReturnIterator(iter)
ms.orig.UnmarshalJSON(iter)
return iter.Error()
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ptrace // import "go.opentelemetry.io/collector/pdata/ptrace"
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// SpanKind is the type of span. Can be used to specify additional relationships between spans
// in addition to a parent/child relationship.
type SpanKind int32
const (
// SpanKindUnspecified represents that the SpanKind is unspecified, it MUST NOT be used.
SpanKindUnspecified = SpanKind(internal.SpanKind_SPAN_KIND_UNSPECIFIED)
// SpanKindInternal indicates that the span represents an internal operation within an application,
// as opposed to an operation happening at the boundaries. Default value.
SpanKindInternal = SpanKind(internal.SpanKind_SPAN_KIND_INTERNAL)
// SpanKindServer indicates that the span covers server-side handling of an RPC or other
// remote network request.
SpanKindServer = SpanKind(internal.SpanKind_SPAN_KIND_SERVER)
// SpanKindClient indicates that the span describes a request to some remote service.
SpanKindClient = SpanKind(internal.SpanKind_SPAN_KIND_CLIENT)
// SpanKindProducer indicates that the span describes a producer sending a message to a broker.
// Unlike CLIENT and SERVER, there is often no direct critical path latency relationship
// between producer and consumer spans.
// A PRODUCER span ends when the message was accepted by the broker while the logical processing of
// the message might span a much longer time.
SpanKindProducer = SpanKind(internal.SpanKind_SPAN_KIND_PRODUCER)
// SpanKindConsumer indicates that the span describes consumer receiving a message from a broker.
// Like the PRODUCER kind, there is often no direct critical path latency relationship between
// producer and consumer spans.
SpanKindConsumer = SpanKind(internal.SpanKind_SPAN_KIND_CONSUMER)
)
// String returns the string representation of the SpanKind.
func (sk SpanKind) String() string {
switch sk {
case SpanKindUnspecified:
return "Unspecified"
case SpanKindInternal:
return "Internal"
case SpanKindServer:
return "Server"
case SpanKindClient:
return "Client"
case SpanKindProducer:
return "Producer"
case SpanKindConsumer:
return "Consumer"
}
return ""
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ptrace // import "go.opentelemetry.io/collector/pdata/ptrace"
import (
"go.opentelemetry.io/collector/pdata/internal"
)
// StatusCode mirrors the codes defined at
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#set-status
type StatusCode int32
const (
StatusCodeUnset = StatusCode(internal.StatusCode_STATUS_CODE_UNSET)
StatusCodeOk = StatusCode(internal.StatusCode_STATUS_CODE_OK)
StatusCodeError = StatusCode(internal.StatusCode_STATUS_CODE_ERROR)
)
// String returns the string representation of the StatusCode.
func (sc StatusCode) String() string {
switch sc {
case StatusCodeUnset:
return "Unset"
case StatusCodeOk:
return "Ok"
case StatusCodeError:
return "Error"
}
return ""
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ptrace // import "go.opentelemetry.io/collector/pdata/ptrace"
// MarkReadOnly marks the Traces as shared so that no further modifications can be done on it.
func (ms Traces) MarkReadOnly() {
ms.getState().MarkReadOnly()
}
// IsReadOnly returns true if this Traces instance is read-only.
func (ms Traces) IsReadOnly() bool {
return ms.getState().IsReadOnly()
}
// SpanCount calculates the total number of spans.
func (ms Traces) SpanCount() int {
spanCount := 0
rss := ms.ResourceSpans()
for i := 0; i < rss.Len(); i++ {
rs := rss.At(i)
ilss := rs.ScopeSpans()
for j := 0; j < ilss.Len(); j++ {
spanCount += ilss.At(j).Spans().Len()
}
}
return spanCount
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlpreceiver // import "go.opentelemetry.io/collector/receiver/otlpreceiver"
import (
"encoding"
"errors"
"fmt"
"net/url"
"path"
"go.opentelemetry.io/collector/component"
)
var _ encoding.TextUnmarshaler = (*SanitizedURLPath)(nil)
func (s *SanitizedURLPath) UnmarshalText(text []byte) error {
u, err := url.Parse(string(text))
if err != nil {
return fmt.Errorf("invalid HTTP URL path set for signal: %w", err)
}
if !path.IsAbs(u.Path) {
u.Path = "/" + u.Path
}
*s = SanitizedURLPath(u.Path)
return nil
}
var _ component.Config = (*Config)(nil)
// Validate checks the receiver configuration is valid
func validateProtocols(p *Protocols) error {
if !p.GRPC.HasValue() && !p.HTTP.HasValue() {
return errors.New("must specify at least one protocol when using the OTLP receiver")
}
return nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlpreceiver // import "go.opentelemetry.io/collector/receiver/otlpreceiver"
import (
spb "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"go.opentelemetry.io/collector/pdata/plog/plogotlp"
"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp"
"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
)
const (
pbContentType = "application/x-protobuf"
jsonContentType = "application/json"
)
var (
pbEncoder = &protoEncoder{}
jsEncoder = &jsonEncoder{}
)
type encoder interface {
unmarshalTracesRequest(buf []byte) (ptraceotlp.ExportRequest, error)
unmarshalMetricsRequest(buf []byte) (pmetricotlp.ExportRequest, error)
unmarshalLogsRequest(buf []byte) (plogotlp.ExportRequest, error)
unmarshalProfilesRequest(buf []byte) (pprofileotlp.ExportRequest, error)
marshalTracesResponse(ptraceotlp.ExportResponse) ([]byte, error)
marshalMetricsResponse(pmetricotlp.ExportResponse) ([]byte, error)
marshalLogsResponse(plogotlp.ExportResponse) ([]byte, error)
marshalProfilesResponse(pprofileotlp.ExportResponse) ([]byte, error)
marshalStatus(rsp *spb.Status) ([]byte, error)
contentType() string
}
type protoEncoder struct{}
func (protoEncoder) unmarshalTracesRequest(buf []byte) (ptraceotlp.ExportRequest, error) {
req := ptraceotlp.NewExportRequest()
err := req.UnmarshalProto(buf)
return req, err
}
func (protoEncoder) unmarshalMetricsRequest(buf []byte) (pmetricotlp.ExportRequest, error) {
req := pmetricotlp.NewExportRequest()
err := req.UnmarshalProto(buf)
return req, err
}
func (protoEncoder) unmarshalLogsRequest(buf []byte) (plogotlp.ExportRequest, error) {
req := plogotlp.NewExportRequest()
err := req.UnmarshalProto(buf)
return req, err
}
func (protoEncoder) unmarshalProfilesRequest(buf []byte) (pprofileotlp.ExportRequest, error) {
req := pprofileotlp.NewExportRequest()
err := req.UnmarshalProto(buf)
return req, err
}
func (protoEncoder) marshalTracesResponse(resp ptraceotlp.ExportResponse) ([]byte, error) {
return resp.MarshalProto()
}
func (protoEncoder) marshalMetricsResponse(resp pmetricotlp.ExportResponse) ([]byte, error) {
return resp.MarshalProto()
}
func (protoEncoder) marshalLogsResponse(resp plogotlp.ExportResponse) ([]byte, error) {
return resp.MarshalProto()
}
func (protoEncoder) marshalProfilesResponse(resp pprofileotlp.ExportResponse) ([]byte, error) {
return resp.MarshalProto()
}
func (protoEncoder) marshalStatus(resp *spb.Status) ([]byte, error) {
return proto.Marshal(resp)
}
func (protoEncoder) contentType() string {
return pbContentType
}
type jsonEncoder struct{}
func (jsonEncoder) unmarshalTracesRequest(buf []byte) (ptraceotlp.ExportRequest, error) {
req := ptraceotlp.NewExportRequest()
err := req.UnmarshalJSON(buf)
return req, err
}
func (jsonEncoder) unmarshalMetricsRequest(buf []byte) (pmetricotlp.ExportRequest, error) {
req := pmetricotlp.NewExportRequest()
err := req.UnmarshalJSON(buf)
return req, err
}
func (jsonEncoder) unmarshalLogsRequest(buf []byte) (plogotlp.ExportRequest, error) {
req := plogotlp.NewExportRequest()
err := req.UnmarshalJSON(buf)
return req, err
}
func (jsonEncoder) unmarshalProfilesRequest(buf []byte) (pprofileotlp.ExportRequest, error) {
req := pprofileotlp.NewExportRequest()
err := req.UnmarshalJSON(buf)
return req, err
}
func (jsonEncoder) marshalTracesResponse(resp ptraceotlp.ExportResponse) ([]byte, error) {
return resp.MarshalJSON()
}
func (jsonEncoder) marshalMetricsResponse(resp pmetricotlp.ExportResponse) ([]byte, error) {
return resp.MarshalJSON()
}
func (jsonEncoder) marshalLogsResponse(resp plogotlp.ExportResponse) ([]byte, error) {
return resp.MarshalJSON()
}
func (jsonEncoder) marshalProfilesResponse(resp pprofileotlp.ExportResponse) ([]byte, error) {
return resp.MarshalJSON()
}
func (jsonEncoder) marshalStatus(resp *spb.Status) ([]byte, error) {
return protojson.Marshal(resp)
}
func (jsonEncoder) contentType() string {
return jsonContentType
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlpreceiver // import "go.opentelemetry.io/collector/receiver/otlpreceiver"
import (
"context"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/consumer/xconsumer"
"go.opentelemetry.io/collector/internal/sharedcomponent"
"go.opentelemetry.io/collector/receiver"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metadata"
"go.opentelemetry.io/collector/receiver/xreceiver"
)
const (
defaultTracesURLPath = "/v1/traces"
defaultMetricsURLPath = "/v1/metrics"
defaultLogsURLPath = "/v1/logs"
defaultProfilesURLPath = "/v1development/profiles"
)
// NewFactory creates a new OTLP receiver factory.
func NewFactory() receiver.Factory {
return xreceiver.NewFactory(
metadata.Type,
createDefaultConfig,
xreceiver.WithTraces(createTraces, metadata.TracesStability),
xreceiver.WithMetrics(createMetrics, metadata.MetricsStability),
xreceiver.WithLogs(createLog, metadata.LogsStability),
xreceiver.WithProfiles(createProfiles, metadata.ProfilesStability),
)
}
// createTraces creates a trace receiver based on provided config.
func createTraces(
_ context.Context,
set receiver.Settings,
cfg component.Config,
nextConsumer consumer.Traces,
) (receiver.Traces, error) {
oCfg := cfg.(*Config)
r, err := receivers.LoadOrStore(
oCfg,
func() (*otlpReceiver, error) {
return newOtlpReceiver(oCfg, &set)
},
)
if err != nil {
return nil, err
}
r.Unwrap().registerTraceConsumer(nextConsumer)
return r, nil
}
// createMetrics creates a metrics receiver based on provided config.
func createMetrics(
_ context.Context,
set receiver.Settings,
cfg component.Config,
consumer consumer.Metrics,
) (receiver.Metrics, error) {
oCfg := cfg.(*Config)
r, err := receivers.LoadOrStore(
oCfg,
func() (*otlpReceiver, error) {
return newOtlpReceiver(oCfg, &set)
},
)
if err != nil {
return nil, err
}
r.Unwrap().registerMetricsConsumer(consumer)
return r, nil
}
// createLog creates a log receiver based on provided config.
func createLog(
_ context.Context,
set receiver.Settings,
cfg component.Config,
consumer consumer.Logs,
) (receiver.Logs, error) {
oCfg := cfg.(*Config)
r, err := receivers.LoadOrStore(
oCfg,
func() (*otlpReceiver, error) {
return newOtlpReceiver(oCfg, &set)
},
)
if err != nil {
return nil, err
}
r.Unwrap().registerLogsConsumer(consumer)
return r, nil
}
// createProfiles creates a trace receiver based on provided config.
func createProfiles(
_ context.Context,
set receiver.Settings,
cfg component.Config,
nextConsumer xconsumer.Profiles,
) (xreceiver.Profiles, error) {
oCfg := cfg.(*Config)
r, err := receivers.LoadOrStore(
oCfg,
func() (*otlpReceiver, error) {
return newOtlpReceiver(oCfg, &set)
},
)
if err != nil {
return nil, err
}
r.Unwrap().registerProfilesConsumer(nextConsumer)
return r, nil
}
// This is the map of already created OTLP receivers for particular configurations.
// We maintain this map because the receiver.Factory is asked trace and metric receivers separately
// when it gets CreateTraces() and CreateMetrics() but they must not
// create separate objects, they must use one otlpReceiver object per configuration.
// When the receiver is shutdown it should be removed from this map so the same configuration
// can be recreated successfully.
var receivers = sharedcomponent.NewMap[*Config, *otlpReceiver]()
// Code generated by mdatagen. DO NOT EDIT.
package otlpreceiver
import (
"errors"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/config/configgrpc"
"go.opentelemetry.io/collector/config/confighttp"
"go.opentelemetry.io/collector/config/configoptional"
"go.opentelemetry.io/collector/config/configtls"
)
type HTTPConfig struct {
// ServerConfig defines settings for creating an HTTP server.
ServerConfig confighttp.ServerConfig `mapstructure:",squash"`
// TracesURLPath is the URL path to receive traces on. If omitted "/v1/traces" will be used.
TracesURLPath SanitizedURLPath `mapstructure:"traces_url_path,omitempty"`
// MetricsURLPath is the URL path to receive metrics on. If omitted "/v1/metrics" will be used.
MetricsURLPath SanitizedURLPath `mapstructure:"metrics_url_path,omitempty"`
// LogsURLPath is the URL path to receive logs on. If omitted "/v1/logs" will be used.
LogsURLPath SanitizedURLPath `mapstructure:"logs_url_path,omitempty"`
// prevent unkeyed literal initialization
_ struct{}
}
func newDefaultHTTPConfig() HTTPConfig {
return HTTPConfig{
ServerConfig: confighttp.NewDefaultServerConfig(),
}
}
// Protocols is the configuration for the supported protocols, currently gRPC and HTTP (Proto and JSON).
type Protocols struct {
// GRPC defines common settings for a gRPC server configuration.
GRPC configoptional.Optional[configgrpc.ServerConfig] `mapstructure:"grpc"`
HTTP configoptional.Optional[HTTPConfig] `mapstructure:"http"`
// prevent unkeyed literal initialization
_ struct{}
}
// Validate validates the Protocols fields according to schema annotations.
// Called by confmap on config resolution. Don't call it explicitly to avoid duplicate errors.
func (c *Protocols) Validate() error {
var err error
if inner_err := validateProtocols(c); inner_err != nil {
err = errors.Join(err, inner_err)
}
return err
}
func newDefaultProtocols() Protocols {
grpc := configgrpc.NewDefaultServerConfig()
grpc.ReadBufferSize = 524288
grpc.NetAddr.Endpoint = "localhost:4317"
http := newDefaultHTTPConfig()
http.ServerConfig.NetAddr.Endpoint = "localhost:4318"
http.ServerConfig.TLS = configoptional.None[configtls.ServerConfig]()
http.ServerConfig.ReadHeaderTimeout = 0
http.ServerConfig.WriteTimeout = 0
http.TracesURLPath = "/v1/traces"
http.MetricsURLPath = "/v1/metrics"
http.LogsURLPath = "/v1/logs"
return Protocols{
GRPC: configoptional.Default(grpc),
HTTP: configoptional.Default(http),
}
}
type SanitizedURLPath string
// Config defines the configuration for OTLP Receiver component.
type Config struct {
// Protocols is the configuration for the supported protocols, currently gRPC and HTTP (Proto and JSON).
Protocols Protocols `mapstructure:"protocols"`
// prevent unkeyed literal initialization
_ struct{}
}
func createDefaultConfig() component.Config {
return &Config{
Protocols: newDefaultProtocols(),
}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package errors // import "go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors"
import (
"net/http"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"go.opentelemetry.io/collector/consumer/consumererror"
)
func GetStatusFromError(err error) error {
s, ok := status.FromError(err)
if !ok {
// Default to a retryable error
// https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#failures
code := codes.Unavailable
if consumererror.IsPermanent(err) {
// If an error is permanent but doesn't have an attached gRPC status, assume it is server-side.
code = codes.Internal
}
s = status.New(code, err.Error())
}
return s.Err()
}
func GetHTTPStatusCodeFromStatus(s *status.Status) int {
// See https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#failures
// to see if a code is retryable.
// See https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#failures-1
// to see a list of retryable http status codes.
switch s.Code() {
// Retryable
case codes.Canceled, codes.DeadlineExceeded, codes.Aborted, codes.OutOfRange, codes.Unavailable, codes.DataLoss:
return http.StatusServiceUnavailable
// Retryable
case codes.ResourceExhausted:
return http.StatusTooManyRequests
// Not Retryable
case codes.InvalidArgument:
return http.StatusBadRequest
// Not Retryable
case codes.Unauthenticated:
return http.StatusUnauthorized
// Not Retryable
case codes.PermissionDenied:
return http.StatusForbidden
// Not Retryable
case codes.Unimplemented:
return http.StatusNotFound
// Not Retryable
default:
return http.StatusInternalServerError
}
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package logs // import "go.opentelemetry.io/collector/receiver/otlpreceiver/internal/logs"
import (
"context"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/pdata/plog/plogotlp"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors"
"go.opentelemetry.io/collector/receiver/receiverhelper"
)
const dataFormatProtobuf = "protobuf"
// Receiver is the type used to handle logs from OpenTelemetry exporters.
type Receiver struct {
plogotlp.UnimplementedGRPCServer
nextConsumer consumer.Logs
obsreport *receiverhelper.ObsReport
}
// New creates a new Receiver reference.
func New(nextConsumer consumer.Logs, obsreport *receiverhelper.ObsReport) *Receiver {
return &Receiver{
nextConsumer: nextConsumer,
obsreport: obsreport,
}
}
// Export implements the service Export logs func.
func (r *Receiver) Export(ctx context.Context, req plogotlp.ExportRequest) (plogotlp.ExportResponse, error) {
ld := req.Logs()
numSpans := ld.LogRecordCount()
if numSpans == 0 {
return plogotlp.NewExportResponse(), nil
}
ctx = r.obsreport.StartLogsOp(ctx)
err := r.nextConsumer.ConsumeLogs(ctx, ld)
r.obsreport.EndLogsOp(ctx, dataFormatProtobuf, numSpans, err)
// Use appropriate status codes for permanent/non-permanent errors
// If we return the error straightaway, then the grpc implementation will set status code to Unknown
// Refer: https://github.com/grpc/grpc-go/blob/v1.59.0/server.go#L1345
// So, convert the error to appropriate grpc status and return the error
// NonPermanent errors will be converted to codes.Unavailable (equivalent to HTTP 503)
// Permanent errors will be converted to codes.InvalidArgument (equivalent to HTTP 400)
if err != nil {
return plogotlp.NewExportResponse(), errors.GetStatusFromError(err)
}
return plogotlp.NewExportResponse(), nil
}
// Code generated by mdatagen. DO NOT EDIT.
package metadata
import (
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/plog"
"go.opentelemetry.io/collector/receiver"
)
// LogsBuilder provides an interface for scrapers to report logs while taking care of all the transformations
// required to produce log representation defined in metadata and user config.
type LogsBuilder struct {
logsBuffer plog.Logs
logRecordsBuffer plog.LogRecordSlice
buildInfo component.BuildInfo // contains version information.
}
// LogBuilderOption applies changes to default logs builder.
type LogBuilderOption interface {
apply(*LogsBuilder)
}
func NewLogsBuilder(settings receiver.Settings) *LogsBuilder {
lb := &LogsBuilder{
logsBuffer: plog.NewLogs(),
logRecordsBuffer: plog.NewLogRecordSlice(),
buildInfo: settings.BuildInfo,
}
return lb
}
// ResourceLogsOption applies changes to provided resource logs.
type ResourceLogsOption interface {
apply(plog.ResourceLogs)
}
type resourceLogsOptionFunc func(plog.ResourceLogs)
func (rlof resourceLogsOptionFunc) apply(rl plog.ResourceLogs) {
rlof(rl)
}
// WithLogsResource sets the provided resource on the emitted ResourceLogs.
// It's recommended to use ResourceBuilder to create the resource.
func WithLogsResource(res pcommon.Resource) ResourceLogsOption {
return resourceLogsOptionFunc(func(rl plog.ResourceLogs) {
res.CopyTo(rl.Resource())
})
}
// AppendLogRecord adds a log record to the logs builder.
func (lb *LogsBuilder) AppendLogRecord(lr plog.LogRecord) {
lr.MoveTo(lb.logRecordsBuffer.AppendEmpty())
}
// EmitForResource saves all the generated logs under a new resource and updates the internal state to be ready for
// recording another set of log records as part of another resource. This function can be helpful when one scraper
// needs to emit logs from several resources. Otherwise calling this function is not required,
// just `Emit` function can be called instead.
// Resource attributes should be provided as ResourceLogsOption arguments.
func (lb *LogsBuilder) EmitForResource(options ...ResourceLogsOption) {
rl := plog.NewResourceLogs()
ils := rl.ScopeLogs().AppendEmpty()
ils.Scope().SetName(ScopeName)
ils.Scope().SetVersion(lb.buildInfo.Version)
for _, op := range options {
op.apply(rl)
}
if lb.logRecordsBuffer.Len() > 0 {
lb.logRecordsBuffer.MoveAndAppendTo(ils.LogRecords())
lb.logRecordsBuffer = plog.NewLogRecordSlice()
}
if ils.LogRecords().Len() > 0 {
rl.MoveTo(lb.logsBuffer.ResourceLogs().AppendEmpty())
}
}
// Emit returns all the logs accumulated by the logs builder and updates the internal state to be ready for
// recording another set of logs. This function will be responsible for applying all the transformations required to
// produce logs representation defined in metadata and user config.
func (lb *LogsBuilder) Emit(options ...ResourceLogsOption) plog.Logs {
lb.EmitForResource(options...)
logs := lb.logsBuffer
lb.logsBuffer = plog.NewLogs()
return logs
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package metrics // import "go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metrics"
import (
"context"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors"
"go.opentelemetry.io/collector/receiver/receiverhelper"
)
const dataFormatProtobuf = "protobuf"
// Receiver is the type used to handle metrics from OpenTelemetry exporters.
type Receiver struct {
pmetricotlp.UnimplementedGRPCServer
nextConsumer consumer.Metrics
obsreport *receiverhelper.ObsReport
}
// New creates a new Receiver reference.
func New(nextConsumer consumer.Metrics, obsreport *receiverhelper.ObsReport) *Receiver {
return &Receiver{
nextConsumer: nextConsumer,
obsreport: obsreport,
}
}
// Export implements the service Export metrics func.
func (r *Receiver) Export(ctx context.Context, req pmetricotlp.ExportRequest) (pmetricotlp.ExportResponse, error) {
md := req.Metrics()
dataPointCount := md.DataPointCount()
if dataPointCount == 0 {
return pmetricotlp.NewExportResponse(), nil
}
ctx = r.obsreport.StartMetricsOp(ctx)
err := r.nextConsumer.ConsumeMetrics(ctx, md)
r.obsreport.EndMetricsOp(ctx, dataFormatProtobuf, dataPointCount, err)
// Use appropriate status codes for permanent/non-permanent errors
// If we return the error straightaway, then the grpc implementation will set status code to Unknown
// Refer: https://github.com/grpc/grpc-go/blob/v1.59.0/server.go#L1345
// So, convert the error to appropriate grpc status and return the error
// NonPermanent errors will be converted to codes.Unavailable (equivalent to HTTP 503)
// Permanent errors will be converted to codes.InvalidArgument (equivalent to HTTP 400)
if err != nil {
return pmetricotlp.NewExportResponse(), errors.GetStatusFromError(err)
}
return pmetricotlp.NewExportResponse(), nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package profiles // import "go.opentelemetry.io/collector/receiver/otlpreceiver/internal/profiles"
import (
"context"
"go.opentelemetry.io/collector/consumer/xconsumer"
"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors"
"go.opentelemetry.io/collector/receiver/receiverhelper/xreceiverhelper"
)
const dataFormatProtobuf = "protobuf"
// Receiver is the type used to handle spans from OpenTelemetry exporters.
type Receiver struct {
pprofileotlp.UnimplementedGRPCServer
nextConsumer xconsumer.Profiles
obsreport *xreceiverhelper.ObsReport
}
// New creates a new Receiver reference.
func New(nextConsumer xconsumer.Profiles, obsreport *xreceiverhelper.ObsReport) *Receiver {
return &Receiver{
nextConsumer: nextConsumer,
obsreport: obsreport,
}
}
// Export implements the service Export profiles func.
func (r *Receiver) Export(ctx context.Context, req pprofileotlp.ExportRequest) (pprofileotlp.ExportResponse, error) {
td := req.Profiles()
// We need to ensure that it propagates the receiver name as a tag
numSamples := td.SampleCount()
if numSamples == 0 {
return pprofileotlp.NewExportResponse(), nil
}
// Collect the counts before calling ConsumeProfiles as the data may be
// mutated downstream.
samplesByType := xreceiverhelper.ProfileSampleCountsByType(td)
ctx = r.obsreport.StartProfilesOp(ctx)
err := r.nextConsumer.ConsumeProfiles(ctx, td)
r.obsreport.EndProfilesOpBySampleType(ctx, dataFormatProtobuf, samplesByType, err)
// Use appropriate status codes for permanent/non-permanent errors
// If we return the error straightaway, then the grpc implementation will set status code to Unknown
// Refer: https://github.com/grpc/grpc-go/blob/v1.59.0/server.go#L1345
// So, convert the error to appropriate grpc status and return the error
// NonPermanent errors will be converted to codes.Unavailable (equivalent to HTTP 503)
// Permanent errors will be converted to codes.InvalidArgument (equivalent to HTTP 400)
if err != nil {
return pprofileotlp.NewExportResponse(), errors.GetStatusFromError(err)
}
return pprofileotlp.NewExportResponse(), nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package trace // import "go.opentelemetry.io/collector/receiver/otlpreceiver/internal/trace"
import (
"context"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors"
"go.opentelemetry.io/collector/receiver/receiverhelper"
)
const dataFormatProtobuf = "protobuf"
// Receiver is the type used to handle spans from OpenTelemetry exporters.
type Receiver struct {
ptraceotlp.UnimplementedGRPCServer
nextConsumer consumer.Traces
obsreport *receiverhelper.ObsReport
}
// New creates a new Receiver reference.
func New(nextConsumer consumer.Traces, obsreport *receiverhelper.ObsReport) *Receiver {
return &Receiver{
nextConsumer: nextConsumer,
obsreport: obsreport,
}
}
// Export implements the service Export traces func.
func (r *Receiver) Export(ctx context.Context, req ptraceotlp.ExportRequest) (ptraceotlp.ExportResponse, error) {
td := req.Traces()
// We need to ensure that it propagates the receiver name as a tag
numSpans := td.SpanCount()
if numSpans == 0 {
return ptraceotlp.NewExportResponse(), nil
}
ctx = r.obsreport.StartTracesOp(ctx)
err := r.nextConsumer.ConsumeTraces(ctx, td)
r.obsreport.EndTracesOp(ctx, dataFormatProtobuf, numSpans, err)
// Use appropriate status codes for permanent/non-permanent errors
// If we return the error straightaway, then the grpc implementation will set status code to Unknown
// Refer: https://github.com/grpc/grpc-go/blob/v1.59.0/server.go#L1345
// So, convert the error to appropriate grpc status and return the error
// NonPermanent errors will be converted to codes.Unavailable (equivalent to HTTP 503)
// Permanent errors will be converted to codes.InvalidArgument (equivalent to HTTP 400)
if err != nil {
return ptraceotlp.NewExportResponse(), errors.GetStatusFromError(err)
}
return ptraceotlp.NewExportResponse(), nil
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlpreceiver // import "go.opentelemetry.io/collector/receiver/otlpreceiver"
import (
"context"
"errors"
"net"
"net/http"
"sync"
"go.uber.org/zap"
"google.golang.org/grpc"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/component/componentstatus"
"go.opentelemetry.io/collector/config/confighttp"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/consumer/xconsumer"
"go.opentelemetry.io/collector/internal/telemetry"
"go.opentelemetry.io/collector/pdata/plog/plogotlp"
"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp"
"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
"go.opentelemetry.io/collector/receiver"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/logs"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metrics"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/profiles"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/trace"
"go.opentelemetry.io/collector/receiver/receiverhelper"
"go.opentelemetry.io/collector/receiver/receiverhelper/xreceiverhelper"
)
// otlpReceiver is the type that exposes Trace and Metrics reception.
type otlpReceiver struct {
cfg *Config
serverGRPC *grpc.Server
serverHTTP *http.Server
nextTraces consumer.Traces
nextMetrics consumer.Metrics
nextLogs consumer.Logs
nextProfiles xconsumer.Profiles
shutdownWG sync.WaitGroup
obsrepGRPC *receiverhelper.ObsReport
obsrepHTTP *receiverhelper.ObsReport
// Profiles are observed separately, as their telemetry is reported per
// sample type.
obsrepProfilesGRPC *xreceiverhelper.ObsReport
obsrepProfilesHTTP *xreceiverhelper.ObsReport
settings *receiver.Settings
}
// newOtlpReceiver just creates the OpenTelemetry receiver services. It is the caller's
// responsibility to invoke the respective Start*Reception methods as well
// as the various Stop*Reception methods to end it.
func newOtlpReceiver(cfg *Config, set *receiver.Settings) (*otlpReceiver, error) {
set.TelemetrySettings = telemetry.DropInjectedAttributes(set.TelemetrySettings, telemetry.SignalKey)
set.Logger.Debug("created signal-agnostic logger")
r := &otlpReceiver{
cfg: cfg,
nextTraces: nil,
nextMetrics: nil,
nextLogs: nil,
nextProfiles: nil,
settings: set,
}
var err error
r.obsrepGRPC, err = receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{
ReceiverID: set.ID,
Transport: "grpc",
ReceiverCreateSettings: *set,
})
if err != nil {
return nil, err
}
r.obsrepHTTP, err = receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{
ReceiverID: set.ID,
Transport: "http",
ReceiverCreateSettings: *set,
})
if err != nil {
return nil, err
}
r.obsrepProfilesGRPC, err = xreceiverhelper.NewObsReport(receiverhelper.ObsReportSettings{
ReceiverID: set.ID,
Transport: "grpc",
ReceiverCreateSettings: *set,
})
if err != nil {
return nil, err
}
r.obsrepProfilesHTTP, err = xreceiverhelper.NewObsReport(receiverhelper.ObsReportSettings{
ReceiverID: set.ID,
Transport: "http",
ReceiverCreateSettings: *set,
})
if err != nil {
return nil, err
}
return r, nil
}
func (r *otlpReceiver) startGRPCServer(ctx context.Context, host component.Host) error {
// If GRPC is not enabled, nothing to start.
if !r.cfg.Protocols.GRPC.HasValue() {
return nil
}
grpcCfg := r.cfg.Protocols.GRPC.Get()
var err error
if r.serverGRPC, err = grpcCfg.ToServer(ctx, host.GetExtensions(), r.settings.TelemetrySettings); err != nil {
return err
}
if r.nextTraces != nil {
ptraceotlp.RegisterGRPCServer(r.serverGRPC, trace.New(r.nextTraces, r.obsrepGRPC))
}
if r.nextMetrics != nil {
pmetricotlp.RegisterGRPCServer(r.serverGRPC, metrics.New(r.nextMetrics, r.obsrepGRPC))
}
if r.nextLogs != nil {
plogotlp.RegisterGRPCServer(r.serverGRPC, logs.New(r.nextLogs, r.obsrepGRPC))
}
if r.nextProfiles != nil {
pprofileotlp.RegisterGRPCServer(r.serverGRPC, profiles.New(r.nextProfiles, r.obsrepProfilesGRPC))
}
var gln net.Listener
if gln, err = grpcCfg.NetAddr.Listen(ctx); err != nil {
return err
}
r.settings.Logger.Info("Starting GRPC server", zap.String("endpoint", gln.Addr().String()))
r.shutdownWG.Go(func() {
if errGrpc := r.serverGRPC.Serve(gln); errGrpc != nil && !errors.Is(errGrpc, grpc.ErrServerStopped) {
componentstatus.ReportStatus(host, componentstatus.NewFatalErrorEvent(errGrpc))
}
})
return nil
}
func (r *otlpReceiver) startHTTPServer(ctx context.Context, host component.Host) error {
// If HTTP is not enabled, nothing to start.
if !r.cfg.Protocols.HTTP.HasValue() {
return nil
}
httpCfg := r.cfg.Protocols.HTTP.Get()
httpMux := http.NewServeMux()
if r.nextTraces != nil {
httpTracesReceiver := trace.New(r.nextTraces, r.obsrepHTTP)
httpMux.HandleFunc(string(httpCfg.TracesURLPath), func(resp http.ResponseWriter, req *http.Request) {
handleTraces(resp, req, httpTracesReceiver)
})
}
if r.nextMetrics != nil {
httpMetricsReceiver := metrics.New(r.nextMetrics, r.obsrepHTTP)
httpMux.HandleFunc(string(httpCfg.MetricsURLPath), func(resp http.ResponseWriter, req *http.Request) {
handleMetrics(resp, req, httpMetricsReceiver)
})
}
if r.nextLogs != nil {
httpLogsReceiver := logs.New(r.nextLogs, r.obsrepHTTP)
httpMux.HandleFunc(string(httpCfg.LogsURLPath), func(resp http.ResponseWriter, req *http.Request) {
handleLogs(resp, req, httpLogsReceiver)
})
}
if r.nextProfiles != nil {
httpProfilesReceiver := profiles.New(r.nextProfiles, r.obsrepProfilesHTTP)
httpMux.HandleFunc(defaultProfilesURLPath, func(resp http.ResponseWriter, req *http.Request) {
handleProfiles(resp, req, httpProfilesReceiver)
})
}
var err error
if r.serverHTTP, err = httpCfg.ServerConfig.ToServer(ctx, host.GetExtensions(), r.settings.TelemetrySettings, httpMux, confighttp.WithErrorHandler(errorHandler)); err != nil {
return err
}
var hln net.Listener
if hln, err = httpCfg.ServerConfig.ToListener(ctx); err != nil {
return err
}
r.settings.Logger.Info("Starting HTTP server", zap.String("endpoint", hln.Addr().String()))
r.shutdownWG.Go(func() {
if errHTTP := r.serverHTTP.Serve(hln); errHTTP != nil && !errors.Is(errHTTP, http.ErrServerClosed) {
componentstatus.ReportStatus(host, componentstatus.NewFatalErrorEvent(errHTTP))
}
})
return nil
}
// Start runs the OTLP receiver's gRPC and HTTP servers, serving
// traces, metrics, logs (and profiles when enabled).
func (r *otlpReceiver) Start(ctx context.Context, host component.Host) error {
if err := r.startGRPCServer(ctx, host); err != nil {
return err
}
if err := r.startHTTPServer(ctx, host); err != nil {
// It's possible that a valid GRPC server configuration was specified,
// but an invalid HTTP configuration. If that's the case, the successfully
// started GRPC server must be shutdown to ensure no goroutines are leaked.
return errors.Join(err, r.Shutdown(ctx))
}
return nil
}
// Shutdown is a method to turn off receiving.
func (r *otlpReceiver) Shutdown(ctx context.Context) error {
var err error
if r.serverHTTP != nil {
err = r.serverHTTP.Shutdown(ctx)
}
if r.serverGRPC != nil {
r.serverGRPC.GracefulStop()
}
r.shutdownWG.Wait()
return err
}
func (r *otlpReceiver) registerTraceConsumer(tc consumer.Traces) {
r.nextTraces = tc
}
func (r *otlpReceiver) registerMetricsConsumer(mc consumer.Metrics) {
r.nextMetrics = mc
}
func (r *otlpReceiver) registerLogsConsumer(lc consumer.Logs) {
r.nextLogs = lc
}
func (r *otlpReceiver) registerProfilesConsumer(tc xconsumer.Profiles) {
r.nextProfiles = tc
}
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlpreceiver // import "go.opentelemetry.io/collector/receiver/otlpreceiver"
import (
"fmt"
"io"
"mime"
"net/http"
"strconv"
"time"
"google.golang.org/grpc/status"
"go.opentelemetry.io/collector/internal/statusutil"
"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/logs"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metrics"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/profiles"
"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/trace"
)
// Pre-computed status with code=Internal to be used in case of a marshaling error.
var fallbackMsg = []byte(`{"code": 13, "message": "failed to marshal error message"}`)
const fallbackContentType = "application/json"
func handleTraces(resp http.ResponseWriter, req *http.Request, tracesReceiver *trace.Receiver) {
enc, ok := readContentType(resp, req)
if !ok {
return
}
body, ok := readAndCloseBody(resp, req, enc)
if !ok {
return
}
otlpReq, err := enc.unmarshalTracesRequest(body)
if err != nil {
writeError(resp, enc, err, http.StatusBadRequest)
return
}
otlpResp, err := tracesReceiver.Export(req.Context(), otlpReq)
if err != nil {
writeError(resp, enc, err, http.StatusInternalServerError)
return
}
msg, err := enc.marshalTracesResponse(otlpResp)
if err != nil {
writeError(resp, enc, err, http.StatusInternalServerError)
return
}
writeResponse(resp, enc.contentType(), http.StatusOK, msg)
}
func handleMetrics(resp http.ResponseWriter, req *http.Request, metricsReceiver *metrics.Receiver) {
enc, ok := readContentType(resp, req)
if !ok {
return
}
body, ok := readAndCloseBody(resp, req, enc)
if !ok {
return
}
otlpReq, err := enc.unmarshalMetricsRequest(body)
if err != nil {
writeError(resp, enc, err, http.StatusBadRequest)
return
}
otlpResp, err := metricsReceiver.Export(req.Context(), otlpReq)
if err != nil {
writeError(resp, enc, err, http.StatusInternalServerError)
return
}
msg, err := enc.marshalMetricsResponse(otlpResp)
if err != nil {
writeError(resp, enc, err, http.StatusInternalServerError)
return
}
writeResponse(resp, enc.contentType(), http.StatusOK, msg)
}
func handleLogs(resp http.ResponseWriter, req *http.Request, logsReceiver *logs.Receiver) {
enc, ok := readContentType(resp, req)
if !ok {
return
}
body, ok := readAndCloseBody(resp, req, enc)
if !ok {
return
}
otlpReq, err := enc.unmarshalLogsRequest(body)
if err != nil {
writeError(resp, enc, err, http.StatusBadRequest)
return
}
otlpResp, err := logsReceiver.Export(req.Context(), otlpReq)
if err != nil {
writeError(resp, enc, err, http.StatusInternalServerError)
return
}
msg, err := enc.marshalLogsResponse(otlpResp)
if err != nil {
writeError(resp, enc, err, http.StatusInternalServerError)
return
}
writeResponse(resp, enc.contentType(), http.StatusOK, msg)
}
func handleProfiles(resp http.ResponseWriter, req *http.Request, profilesReceiver *profiles.Receiver) {
enc, ok := readContentType(resp, req)
if !ok {
return
}
if err := pprofileotlp.ValidateDevelopmentVersion(req.Header.Values(pprofileotlp.DevelopmentVersionHeader)); err != nil {
writeError(resp, enc, err, http.StatusBadRequest)
return
}
body, ok := readAndCloseBody(resp, req, enc)
if !ok {
return
}
otlpReq, err := enc.unmarshalProfilesRequest(body)
if err != nil {
writeError(resp, enc, err, http.StatusBadRequest)
return
}
otlpResp, err := profilesReceiver.Export(req.Context(), otlpReq)
if err != nil {
writeError(resp, enc, err, http.StatusInternalServerError)
return
}
msg, err := enc.marshalProfilesResponse(otlpResp)
if err != nil {
writeError(resp, enc, err, http.StatusInternalServerError)
return
}
writeResponse(resp, enc.contentType(), http.StatusOK, msg)
}
func readContentType(resp http.ResponseWriter, req *http.Request) (encoder, bool) {
if req.Method != http.MethodPost {
handleUnmatchedMethod(resp)
return nil, false
}
switch getMimeTypeFromContentType(req.Header.Get("Content-Type")) {
case pbContentType:
return pbEncoder, true
case jsonContentType:
return jsEncoder, true
default:
handleUnmatchedContentType(resp)
return nil, false
}
}
func readAndCloseBody(resp http.ResponseWriter, req *http.Request, enc encoder) ([]byte, bool) {
body, err := io.ReadAll(req.Body)
if err != nil {
writeError(resp, enc, err, http.StatusBadRequest)
return nil, false
}
if err = req.Body.Close(); err != nil {
writeError(resp, enc, err, http.StatusBadRequest)
return nil, false
}
return body, true
}
// writeError encodes the HTTP error inside a rpc.Status message as required by the OTLP protocol.
func writeError(w http.ResponseWriter, encoder encoder, err error, statusCode int) {
s, ok := status.FromError(err)
if ok {
statusCode = errors.GetHTTPStatusCodeFromStatus(s)
} else {
s = statusutil.NewStatusFromMsgAndHTTPCode(err.Error(), statusCode)
}
writeStatusResponse(w, encoder, statusCode, s)
}
// errorHandler encodes the HTTP error message inside a rpc.Status message as required
// by the OTLP protocol.
func errorHandler(w http.ResponseWriter, r *http.Request, errMsg string, statusCode int) {
s := statusutil.NewStatusFromMsgAndHTTPCode(errMsg, statusCode)
switch getMimeTypeFromContentType(r.Header.Get("Content-Type")) {
case pbContentType:
writeStatusResponse(w, pbEncoder, statusCode, s)
default:
// Fall back to JSON for any Content-Type that isn't protobuf.
// Preserve the original status code so client errors (4xx) aren't
// reported as server faults.
writeStatusResponse(w, jsEncoder, statusCode, s)
}
}
func writeStatusResponse(w http.ResponseWriter, enc encoder, statusCode int, st *status.Status) {
// https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#otlphttp-throttling
if statusCode == http.StatusTooManyRequests || statusCode == http.StatusServiceUnavailable {
retryInfo := statusutil.GetRetryInfo(st)
// Check if server returned throttling information.
if retryInfo != nil {
// We are throttled. Wait before retrying as requested by the server.
// The value of Retry-After field can be either an HTTP-date or a number of
// seconds to delay after the response is received. See https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.3
//
// Retry-After = HTTP-date / delay-seconds
//
// Use delay-seconds since is easier to format as well as does not require clock synchronization.
w.Header().Set("Retry-After", strconv.FormatInt(int64(retryInfo.GetRetryDelay().AsDuration()/time.Second), 10))
}
}
msg, err := enc.marshalStatus(st.Proto())
if err != nil {
writeResponse(w, fallbackContentType, http.StatusInternalServerError, fallbackMsg)
return
}
writeResponse(w, enc.contentType(), statusCode, msg)
}
func writeResponse(w http.ResponseWriter, contentType string, statusCode int, msg []byte) {
w.Header().Set("Content-Type", contentType)
w.WriteHeader(statusCode)
// Nothing we can do with the error if we cannot write to the response.
_, _ = w.Write(msg) // #nosec G705 -- msg is an OTLP payload written with an explicit, non-HTML Content-Type set above
}
func getMimeTypeFromContentType(contentType string) string {
mediatype, _, err := mime.ParseMediaType(contentType)
if err != nil {
return ""
}
return mediatype
}
func handleUnmatchedMethod(resp http.ResponseWriter) {
hst := http.StatusMethodNotAllowed
writeResponse(resp, "text/plain", hst, fmt.Appendf(nil, "%v method not allowed, supported: [POST]", hst))
}
func handleUnmatchedContentType(resp http.ResponseWriter) {
hst := http.StatusUnsupportedMediaType
writeResponse(resp, "text/plain", hst, fmt.Appendf(nil, "%v unsupported media type, supported: [%s, %s]", hst, jsonContentType, pbContentType))
}