// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package attribute

import (
	
	
	
	
	
	
	
	
	
	

	attribute 
)

//go:generate stringer -type=Type

// Type describes the kind of data a [Value] holds.
type Type int // nolint: revive  // redefines builtin Type.

// Value represents the value in key-value pairs.
//
// Note that the zero value is a valid empty value.
type Value struct {
	vtype    Type
	numeric  uint64
	stringly string
	slice    any
}

const (
	// EMPTY identifies a Value with no data.
	EMPTY Type = iota
	// BOOL identifies a Value containing a bool.
	BOOL
	// INT64 identifies a Value containing an int64.
	INT64
	// FLOAT64 identifies a Value containing a float64.
	FLOAT64
	// STRING identifies a Value containing a string.
	STRING
	// BOOLSLICE identifies a Value containing a []bool.
	BOOLSLICE
	// INT64SLICE identifies a Value containing a []int64.
	INT64SLICE
	// FLOAT64SLICE identifies a Value containing a []float64.
	FLOAT64SLICE
	// STRINGSLICE identifies a Value containing a []string.
	STRINGSLICE
	// BYTESLICE identifies a Value containing a []byte.
	BYTESLICE
	// SLICE identifies a Value containing a []Value.
	SLICE
	// MAP identifies a Value containing a []KeyValue representation of a map.
	//
	// Note that MAP values may contain duplicate keys if duplicate keys are
	// provided when creating the value.
	MAP
	// INVALID is used for a Value with no value set.
	//
	// Deprecated: Use EMPTY instead as an empty value is a valid value.
	INVALID = EMPTY
)

// BoolValue returns a [Value] for a bool value.
func ( bool) Value {
	return Value{
		vtype:   BOOL,
		numeric: boolToRaw(),
	}
}

// BoolSliceValue returns a [Value] for a []bool value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func ( []bool) Value {
	return Value{vtype: BOOLSLICE, slice: attribute.SliceValue()}
}

// IntValue returns a [Value] for an int value.
//
// It is provided as a convenience for [Int64Value].
func ( int) Value {
	return Int64Value(int64())
}

// IntSliceValue returns a [Value] for a []int value.
//
// It is provided as a convenience for [Int64SliceValue].
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func ( []int) Value {
	 := Value{vtype: INT64SLICE}

	// Avoid the common tiny-slice cases from allocating a new slice.
	switch len() {
	case 0:
		.slice = [0]int64{}
	case 1:
		.slice = [1]int64{int64([0])}
	case 2:
		.slice = [2]int64{int64([0]), int64([1])}
	case 3:
		.slice = [3]int64{int64([0]), int64([1]), int64([2])}
	default:
		// Fallback to a new slice for larger slices.
		 := make([]int64, len())
		for ,  := range  {
			[] = int64()
		}
		.slice = attribute.SliceValue()
	}

	return 
}

// Int64Value returns a [Value] for an int64 value.
func ( int64) Value {
	return Value{
		vtype:   INT64,
		numeric: int64ToRaw(),
	}
}

// Int64SliceValue returns a [Value] for a []int64 value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func ( []int64) Value {
	return Value{vtype: INT64SLICE, slice: attribute.SliceValue()}
}

// Float64Value returns a [Value] for a float64 value.
func ( float64) Value {
	return Value{
		vtype:   FLOAT64,
		numeric: float64ToRaw(),
	}
}

// Float64SliceValue returns a [Value] for a []float64 value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func ( []float64) Value {
	return Value{vtype: FLOAT64SLICE, slice: attribute.SliceValue()}
}

// StringValue returns a [Value] for a string value.
func ( string) Value {
	return Value{
		vtype:    STRING,
		stringly: ,
	}
}

// StringSliceValue returns a [Value] for a []string value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func ( []string) Value {
	return Value{vtype: STRINGSLICE, slice: attribute.SliceValue()}
}

// ByteSliceValue returns a [Value] for a []byte value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func ( []byte) Value {
	return Value{
		vtype:    BYTESLICE,
		stringly: string(),
	}
}

// SliceValue returns a [Value] for a []Value value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func ( ...Value) Value {
	return Value{vtype: SLICE, slice: sliceValue()}
}

// MapValue returns a [Value] for a []KeyValue value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// Users should avoid providing duplicate keys; many receivers handle maps
// containing duplicate keys unpredictably.
//
// The order of v is not preserved.
func ( ...KeyValue) Value {
	return Value{vtype: MAP, slice: mapValue()}
}

// Type returns v's type.
func ( Value) () Type {
	return .vtype
}

// AsBool returns the bool value. Make sure that the Value's type is
// BOOL.
func ( Value) () bool {
	return rawToBool(.numeric)
}

// AsBoolSlice returns the []bool value. Make sure that the Value's type is
// BOOLSLICE.
func ( Value) () []bool {
	if .vtype != BOOLSLICE {
		return nil
	}
	return .asBoolSlice()
}

func ( Value) () []bool {
	return attribute.AsSlice[bool](.slice)
}

// AsInt64 returns the int64 value. Make sure that the Value's type is
// INT64.
func ( Value) () int64 {
	return rawToInt64(.numeric)
}

// AsInt64Slice returns the []int64 value. Make sure that the Value's type is
// INT64SLICE.
func ( Value) () []int64 {
	if .vtype != INT64SLICE {
		return nil
	}
	return .asInt64Slice()
}

func ( Value) () []int64 {
	return attribute.AsSlice[int64](.slice)
}

// AsFloat64 returns the float64 value. Make sure that the Value's
// type is FLOAT64.
func ( Value) () float64 {
	return rawToFloat64(.numeric)
}

// AsFloat64Slice returns the []float64 value. Make sure that the Value's type is
// FLOAT64SLICE.
func ( Value) () []float64 {
	if .vtype != FLOAT64SLICE {
		return nil
	}
	return .asFloat64Slice()
}

func ( Value) () []float64 {
	return attribute.AsSlice[float64](.slice)
}

// AsString returns the string value. Make sure that the Value's type
// is STRING.
func ( Value) () string {
	return .stringly
}

// AsStringSlice returns the []string value. Make sure that the Value's type is
// STRINGSLICE.
func ( Value) () []string {
	if .vtype != STRINGSLICE {
		return nil
	}
	return .asStringSlice()
}

func ( Value) () []string {
	return attribute.AsSlice[string](.slice)
}

// AsSlice returns the []Value value. Make sure that the Value's type is
// SLICE.
func ( Value) () []Value {
	if .vtype != SLICE {
		return nil
	}
	return .asSlice()
}

func ( Value) () []Value {
	switch vals := .slice.(type) {
	case [0]Value:
		return []Value{}
	case [1]Value:
		return []Value{[0]}
	case [2]Value:
		return []Value{[0], [1]}
	case [3]Value:
		return []Value{[0], [1], [2]}
	case [4]Value:
		return []Value{[0], [1], [2], [3]}
	case [5]Value:
		return []Value{[0], [1], [2], [3], [4]}
	default:
		return asValueSliceReflect(.slice)
	}
}

func ( any) []Value {
	 := reflect.ValueOf()
	if !.IsValid() || .Kind() != reflect.Array || .Type().Elem() != reflect.TypeFor[Value]() {
		return nil
	}
	 := make([]Value, .Len())
	if len() > 0 {
		_ = reflect.Copy(reflect.ValueOf(), )
	}
	return 
}

// AsMap returns the []KeyValue value. Make sure that the Value's type is
// MAP.
//
// The returned slice is sorted by key and may differ from the order
// provided when creating the map value.
//
// The returned slice may contain duplicate keys if duplicate keys were
// provided when creating the map value. Callers should not assume the returned
// keys are unique.
func ( Value) () []KeyValue {
	if .vtype != MAP {
		return nil
	}
	return .asMap()
}

func ( Value) () []KeyValue {
	switch vals := .slice.(type) {
	case [0]KeyValue:
		return []KeyValue{}
	case [1]KeyValue:
		return []KeyValue{[0]}
	case [2]KeyValue:
		return []KeyValue{[0], [1]}
	case [3]KeyValue:
		return []KeyValue{[0], [1], [2]}
	case [4]KeyValue:
		return []KeyValue{[0], [1], [2], [3]}
	case [5]KeyValue:
		return []KeyValue{[0], [1], [2], [3], [4]}
	default:
		return asKeyValueSliceReflect(.slice)
	}
}

func ( any) []KeyValue {
	 := reflect.ValueOf()
	if !.IsValid() || .Kind() != reflect.Array || .Type().Elem() != reflect.TypeFor[KeyValue]() {
		return nil
	}
	 := make([]KeyValue, .Len())
	if len() > 0 {
		_ = reflect.Copy(reflect.ValueOf(), )
	}
	return 
}

// AsByteSlice returns the bytes value. Make sure that the Value's type
// is BYTESLICE.
func ( Value) () []byte {
	if .vtype != BYTESLICE {
		return nil
	}
	return .asByteSlice()
}

func ( Value) () []byte {
	return []byte(.stringly)
}

type unknownValueType struct{}

// AsInterface returns Value's data as any.
func ( Value) () any {
	switch .Type() {
	case BOOL:
		return .AsBool()
	case BOOLSLICE:
		return .asBoolSlice()
	case INT64:
		return .AsInt64()
	case INT64SLICE:
		return .asInt64Slice()
	case FLOAT64:
		return .AsFloat64()
	case FLOAT64SLICE:
		return .asFloat64Slice()
	case STRING:
		return .stringly
	case STRINGSLICE:
		return .asStringSlice()
	case BYTESLICE:
		return .asByteSlice()
	case SLICE:
		return .asSlice()
	case MAP:
		return .asMap()
	case EMPTY:
		return nil
	}
	return unknownValueType{}
}

// String returns a string representation of Value using the
// [OpenTelemetry AnyValue representation for non-OTLP protocols] rules.
//
// Strings are returned as-is without JSON quoting, booleans and integers use
// JSON literals, floating-point values use JSON numbers except that NaN and
// ±Inf are rendered as NaN, Infinity, and -Infinity, byte slices are
// base64-encoded, empty values are the empty string, slices are encoded as JSON
// arrays, and maps are encoded as JSON objects. String, byte, and special
// floating-point values inside arrays and maps are encoded as JSON strings, and
// empty values inside arrays and maps are encoded as null.
//
// [OpenTelemetry AnyValue representation for non-OTLP protocols]: https://opentelemetry.io/docs/specs/otel/common/#anyvalue-representation-for-non-otlp-protocols
func ( Value) () string {
	switch .Type() {
	case BOOL:
		return strconv.FormatBool(.AsBool())
	case BOOLSLICE:
		return formatBoolSliceValue(.slice)
	case INT64:
		return strconv.FormatInt(.AsInt64(), 10)
	case INT64SLICE:
		return formatInt64SliceValue(.slice)
	case FLOAT64:
		return formatFloat64(.AsFloat64())
	case FLOAT64SLICE:
		return formatFloat64SliceValue(.slice)
	case STRING:
		return .stringly
	case STRINGSLICE:
		return formatStringSliceValue(.slice)
	case BYTESLICE:
		return formatByteSlice(.stringly)
	case SLICE:
		return formatValueSliceValue(.slice)
	case MAP:
		return formatMapValue(.slice)
	case EMPTY:
		return ""
	default:
		return "unknown"
	}
}

// Emit returns a string representation of Value's data.
//
// Deprecated: Use [Value.String] instead.
func ( Value) () string {
	switch .Type() {
	case BOOLSLICE:
		return fmt.Sprint(.asBoolSlice())
	case BOOL:
		return strconv.FormatBool(.AsBool())
	case INT64SLICE:
		,  := json.Marshal(.asInt64Slice())
		if  != nil {
			return fmt.Sprintf("invalid: %v", .asInt64Slice())
		}
		return string()
	case INT64:
		return strconv.FormatInt(.AsInt64(), 10)
	case FLOAT64SLICE:
		,  := json.Marshal(.asFloat64Slice())
		if  != nil {
			return fmt.Sprintf("invalid: %v", .asFloat64Slice())
		}
		return string()
	case FLOAT64:
		return fmt.Sprint(.AsFloat64())
	case STRINGSLICE:
		,  := json.Marshal(.asStringSlice())
		if  != nil {
			return fmt.Sprintf("invalid: %v", .asStringSlice())
		}
		return string()
	case STRING:
		return .stringly
	case BYTESLICE:
		return formatByteSlice(.stringly)
	case SLICE:
		return formatValueSliceValue(.slice)
	case MAP:
		return formatMapValue(.slice)
	case EMPTY:
		return ""
	default:
		return "unknown"
	}
}

const (
	jsonArrayBracketsLen   = len("[]")
	boolArrayElemMaxLen    = len("false")
	int64ArrayElemMaxLen   = len("-9223372036854775808")
	float64ArrayElemMaxLen = len("-1.7976931348623157e+308")
	commaLen               = len(",")
)

func ( []Value) any {
	switch len() {
	case 0:
		return [0]Value{}
	case 1:
		return [1]Value{[0]}
	case 2:
		return [2]Value{[0], [1]}
	case 3:
		return [3]Value{[0], [1], [2]}
	case 4:
		return [4]Value{[0], [1], [2], [3]}
	case 5:
		return [5]Value{[0], [1], [2], [3], [4]}
	default:
		return sliceValueReflect()
	}
}

func ( []Value) any {
	 := reflect.New(reflect.ArrayOf(len(), reflect.TypeFor[Value]())).Elem()
	reflect.Copy(, reflect.ValueOf())
	return .Interface()
}

func ( []KeyValue) any {
	switch len() {
	case 0:
		return [0]KeyValue{}
	case 1:
		return [1]KeyValue{[0]}
	case 2:
		 := [2]KeyValue{[0], [1]}
		sortKeyValues([:])
		return 
	case 3:
		 := [3]KeyValue{[0], [1], [2]}
		sortKeyValues([:])
		return 
	case 4:
		 := [4]KeyValue{[0], [1], [2], [3]}
		sortKeyValues([:])
		return 
	case 5:
		 := [5]KeyValue{[0], [1], [2], [3], [4]}
		sortKeyValues([:])
		return 
	default:
		return mapValueReflect()
	}
}

func ( []KeyValue) any {
	 := reflect.New(reflect.ArrayOf(len(), reflect.TypeFor[KeyValue]())).Elem()
	reflect.Copy(, reflect.ValueOf())
	 := .Slice(0, len()).Interface().([]KeyValue)
	sortKeyValues()
	return .Interface()
}

func ( []KeyValue) {
	slices.SortStableFunc(, func(,  KeyValue) int {
		return cmp.Compare(.Key, .Key)
	})
}

func ( any) string {
	switch vals := .(type) {
	case [0]bool:
		return "[]"
	case [1]bool:
		return formatBoolSlice([:])
	case [2]bool:
		return formatBoolSlice([:])
	case [3]bool:
		return formatBoolSlice([:])
	default:
		return formatBoolSliceReflect()
	}
}

func ( []bool) string {
	var  strings.Builder
	appendBoolSlice(&, )
	return .String()
}

func ( any) string {
	var  strings.Builder
	appendBoolSliceReflect(&, reflect.ValueOf())
	return .String()
}

func ( *strings.Builder,  any) {
	switch vals := .(type) {
	case [0]bool:
		_, _ = .WriteString("[]")
	case [1]bool:
		appendBoolSlice(, [:])
	case [2]bool:
		appendBoolSlice(, [:])
	case [3]bool:
		appendBoolSlice(, [:])
	default:
		appendBoolSliceReflect(, reflect.ValueOf())
	}
}

func ( *strings.Builder,  []bool) {
	.Grow(jsonArrayBracketsLen + len()*(boolArrayElemMaxLen+commaLen))
	_ = .WriteByte('[')
	for ,  := range  {
		if  > 0 {
			_ = .WriteByte(',')
		}
		if  {
			_, _ = .WriteString("true")
		} else {
			_, _ = .WriteString("false")
		}
	}
	_ = .WriteByte(']')
}

func ( *strings.Builder,  reflect.Value) {
	.Grow(jsonArrayBracketsLen + .Len()*(boolArrayElemMaxLen+commaLen))
	_ = .WriteByte('[')
	for  := 0;  < .Len(); ++ {
		if  > 0 {
			_ = .WriteByte(',')
		}
		if .Index().Bool() {
			_, _ = .WriteString("true")
		} else {
			_, _ = .WriteString("false")
		}
	}
	_ = .WriteByte(']')
}

func ( any) string {
	switch vals := .(type) {
	case [0]int64:
		return "[]"
	case [1]int64:
		return formatInt64Slice([:])
	case [2]int64:
		return formatInt64Slice([:])
	case [3]int64:
		return formatInt64Slice([:])
	default:
		return formatInt64SliceReflect()
	}
}

func ( []int64) string {
	var  strings.Builder
	appendInt64Slice(&, )
	return .String()
}

func ( any) string {
	var  strings.Builder
	appendInt64SliceReflect(&, reflect.ValueOf())
	return .String()
}

func ( *strings.Builder,  any) {
	switch vals := .(type) {
	case [0]int64:
		_, _ = .WriteString("[]")
	case [1]int64:
		appendInt64Slice(, [:])
	case [2]int64:
		appendInt64Slice(, [:])
	case [3]int64:
		appendInt64Slice(, [:])
	default:
		appendInt64SliceReflect(, reflect.ValueOf())
	}
}

func ( *strings.Builder,  []int64) {
	.Grow(jsonArrayBracketsLen + len()*(int64ArrayElemMaxLen+commaLen))
	_ = .WriteByte('[')

	var  [int64ArrayElemMaxLen]byte
	for ,  := range  {
		if  > 0 {
			_ = .WriteByte(',')
		}
		 := strconv.AppendInt([:0], , 10)
		_, _ = .Write()
	}

	_ = .WriteByte(']')
}

func ( *strings.Builder,  reflect.Value) {
	.Grow(jsonArrayBracketsLen + .Len()*(int64ArrayElemMaxLen+commaLen))
	_ = .WriteByte('[')

	var  [int64ArrayElemMaxLen]byte
	for  := 0;  < .Len(); ++ {
		if  > 0 {
			_ = .WriteByte(',')
		}
		 := strconv.AppendInt([:0], .Index().Int(), 10)
		_, _ = .Write()
	}

	_ = .WriteByte(']')
}

func ( float64) string {
	switch {
	case math.IsNaN():
		return "NaN"
	case math.IsInf(, 1):
		return "Infinity"
	case math.IsInf(, -1):
		return "-Infinity"
	default:
		return strconv.FormatFloat(, 'g', -1, 64)
	}
}

func ( any) string {
	switch vals := .(type) {
	case [0]float64:
		return "[]"
	case [1]float64:
		return formatFloat64Slice([:])
	case [2]float64:
		return formatFloat64Slice([:])
	case [3]float64:
		return formatFloat64Slice([:])
	default:
		return formatFloat64SliceReflect()
	}
}

func ( []float64) string {
	var  strings.Builder
	appendFloat64Slice(&, )
	return .String()
}

func ( any) string {
	var  strings.Builder
	appendFloat64SliceReflect(&, reflect.ValueOf())
	return .String()
}

func ( *strings.Builder,  any) {
	switch vals := .(type) {
	case [0]float64:
		_, _ = .WriteString("[]")
	case [1]float64:
		appendFloat64Slice(, [:])
	case [2]float64:
		appendFloat64Slice(, [:])
	case [3]float64:
		appendFloat64Slice(, [:])
	default:
		appendFloat64SliceReflect(, reflect.ValueOf())
	}
}

func ( *strings.Builder,  []float64) {
	.Grow(jsonArrayBracketsLen + len()*(float64ArrayElemMaxLen+commaLen))
	_ = .WriteByte('[')

	var  [float64ArrayElemMaxLen]byte
	for ,  := range  {
		if  > 0 {
			_ = .WriteByte(',')
		}

		switch {
		case math.IsNaN():
			_, _ = .WriteString(`"NaN"`)
		case math.IsInf(, 1):
			_, _ = .WriteString(`"Infinity"`)
		case math.IsInf(, -1):
			_, _ = .WriteString(`"-Infinity"`)
		default:
			 := strconv.AppendFloat([:0], , 'g', -1, 64)
			_, _ = .Write()
		}
	}

	_ = .WriteByte(']')
}

func ( *strings.Builder,  reflect.Value) {
	.Grow(jsonArrayBracketsLen + .Len()*(float64ArrayElemMaxLen+commaLen))
	_ = .WriteByte('[')

	var  [float64ArrayElemMaxLen]byte
	for  := 0;  < .Len(); ++ {
		if  > 0 {
			_ = .WriteByte(',')
		}
		 := .Index().Float()
		switch {
		case math.IsNaN():
			_, _ = .WriteString(`"NaN"`)
		case math.IsInf(, 1):
			_, _ = .WriteString(`"Infinity"`)
		case math.IsInf(, -1):
			_, _ = .WriteString(`"-Infinity"`)
		default:
			 := strconv.AppendFloat([:0], , 'g', -1, 64)
			_, _ = .Write()
		}
	}

	_ = .WriteByte(']')
}

func ( any) string {
	switch vals := .(type) {
	case [0]string:
		return "[]"
	case [1]string:
		return formatStringSlice([:])
	case [2]string:
		return formatStringSlice([:])
	case [3]string:
		return formatStringSlice([:])
	default:
		return formatStringSliceReflect()
	}
}

func ( []string) string {
	var  strings.Builder
	appendStringSlice(&, )
	return .String()
}

func ( any) string {
	var  strings.Builder
	appendStringSliceReflect(&, reflect.ValueOf())
	return .String()
}

func ( *strings.Builder,  any) {
	switch vals := .(type) {
	case [0]string:
		_, _ = .WriteString("[]")
	case [1]string:
		appendStringSlice(, [:])
	case [2]string:
		appendStringSlice(, [:])
	case [3]string:
		appendStringSlice(, [:])
	default:
		appendStringSliceReflect(, reflect.ValueOf())
	}
}

func ( *strings.Builder,  []string) {
	 := jsonArrayBracketsLen
	for ,  := range  {
		 += len() + commaLen + 2 // Account for JSON string quotes and comma.
	}

	.Grow()
	_ = .WriteByte('[')
	for ,  := range  {
		if  > 0 {
			_ = .WriteByte(',')
		}
		appendJSONString(, )
	}
	_ = .WriteByte(']')
}

func ( *strings.Builder,  reflect.Value) {
	 := jsonArrayBracketsLen
	for  := 0;  < .Len(); ++ {
		 += len(.Index().String()) + commaLen + 2 // Account for JSON string quotes and comma.
	}

	.Grow()
	_ = .WriteByte('[')
	for  := 0;  < .Len(); ++ {
		if  > 0 {
			_ = .WriteByte(',')
		}
		appendJSONString(, .Index().String())
	}
	_ = .WriteByte(']')
}

func ( string) string {
	var  strings.Builder
	appendBase64(&, )
	return .String()
}

func ( any) string {
	switch vals := .(type) {
	case [0]Value:
		return "[]"
	case [1]Value:
		return formatValueSlice([:])
	case [2]Value:
		return formatValueSlice([:])
	case [3]Value:
		return formatValueSlice([:])
	case [4]Value:
		return formatValueSlice([:])
	case [5]Value:
		return formatValueSlice([:])
	default:
		return formatValueSliceReflect()
	}
}

func ( []Value) string {
	var  strings.Builder
	appendValueSlice(&, )
	return .String()
}

func ( any) string {
	var  strings.Builder
	appendValueSliceReflect(&, reflect.ValueOf())
	return .String()
}

func ( any) string {
	switch vals := .(type) {
	case [0]KeyValue:
		return "{}"
	case [1]KeyValue:
		return formatMap([:])
	case [2]KeyValue:
		return formatMap([:])
	case [3]KeyValue:
		return formatMap([:])
	case [4]KeyValue:
		return formatMap([:])
	case [5]KeyValue:
		return formatMap([:])
	default:
		return formatMapReflect()
	}
}

func ( []KeyValue) string {
	var  strings.Builder
	appendMap(&, )
	return .String()
}

func ( any) string {
	var  strings.Builder
	appendMapReflect(&, reflect.ValueOf())
	return .String()
}

func ( *strings.Builder,  any) {
	switch vals := .(type) {
	case [0]Value:
		_, _ = .WriteString("[]")
	case [1]Value:
		appendValueSlice(, [:])
	case [2]Value:
		appendValueSlice(, [:])
	case [3]Value:
		appendValueSlice(, [:])
	case [4]Value:
		appendValueSlice(, [:])
	case [5]Value:
		appendValueSlice(, [:])
	default:
		appendValueSliceReflect(, reflect.ValueOf())
	}
}

func ( *strings.Builder,  []Value) {
	// Estimate 10 bytes per value for small values and commas.
	.Grow(jsonArrayBracketsLen + len()*commaLen + len()*10)
	_ = .WriteByte('[')
	for ,  := range  {
		if  > 0 {
			_ = .WriteByte(',')
		}
		appendJSONValue(, )
	}
	_ = .WriteByte(']')
}

func ( *strings.Builder,  reflect.Value) {
	// Estimate 10 bytes per value for small values and commas.
	.Grow(jsonArrayBracketsLen + .Len()*commaLen + .Len()*10)
	_ = .WriteByte('[')
	for  := 0;  < .Len(); ++ {
		if  > 0 {
			_ = .WriteByte(',')
		}
		appendJSONValue(, .Index().Interface().(Value))
	}
	_ = .WriteByte(']')
}

func ( *strings.Builder,  any) {
	switch vals := .(type) {
	case [0]KeyValue:
		_, _ = .WriteString("{}")
	case [1]KeyValue:
		appendMap(, [:])
	case [2]KeyValue:
		appendMap(, [:])
	case [3]KeyValue:
		appendMap(, [:])
	case [4]KeyValue:
		appendMap(, [:])
	case [5]KeyValue:
		appendMap(, [:])
	default:
		appendMapReflect(, reflect.ValueOf())
	}
}

func ( *strings.Builder,  []KeyValue) {
	// Estimate 32 bytes per value for small values, plus key quotes, colon,
	// and commas. Escaped keys and larger values grow the builder as needed.
	 := len("{}") + len()*commaLen + len()*32
	for ,  := range  {
		 += len(.Key) + len(`"":`)
	}

	.Grow()
	_ = .WriteByte('{')
	for ,  := range  {
		if  > 0 {
			_ = .WriteByte(',')
		}
		appendJSONString(, string(.Key))
		_ = .WriteByte(':')
		appendJSONValue(, .Value)
	}
	_ = .WriteByte('}')
}

func ( *strings.Builder,  reflect.Value) {
	// Estimate 32 bytes per value for small values, plus key quotes, colon,
	// and commas. Escaped keys and larger values grow the builder as needed.
	 := len("{}") + .Len()*commaLen + .Len()*32
	for  := 0;  < .Len(); ++ {
		 += len(.Index().Field(0).String()) + len(`"":`)
	}

	.Grow()
	_ = .WriteByte('{')
	for  := 0;  < .Len(); ++ {
		if  > 0 {
			_ = .WriteByte(',')
		}
		 := .Index().Interface().(KeyValue)
		appendJSONString(, string(.Key))
		_ = .WriteByte(':')
		appendJSONValue(, .Value)
	}
	_ = .WriteByte('}')
}

func ( *strings.Builder,  Value) {
	switch .Type() {
	case BOOL:
		if .AsBool() {
			_, _ = .WriteString("true")
		} else {
			_, _ = .WriteString("false")
		}
	case BOOLSLICE:
		appendBoolSliceValue(, .slice)
	case INT64:
		var  [int64ArrayElemMaxLen]byte
		 := strconv.AppendInt([:0], .AsInt64(), 10)
		_, _ = .Write()
	case INT64SLICE:
		appendInt64SliceValue(, .slice)
	case FLOAT64:
		 := .AsFloat64()
		switch {
		case math.IsNaN():
			appendJSONString(, "NaN")
		case math.IsInf(, 1):
			appendJSONString(, "Infinity")
		case math.IsInf(, -1):
			appendJSONString(, "-Infinity")
		default:
			var  [float64ArrayElemMaxLen]byte
			 := strconv.AppendFloat([:0], , 'g', -1, 64)
			_, _ = .Write()
		}
	case FLOAT64SLICE:
		appendFloat64SliceValue(, .slice)
	case STRING:
		appendJSONString(, .stringly)
	case STRINGSLICE:
		appendStringSliceValue(, .slice)
	case BYTESLICE:
		_ = .WriteByte('"')
		appendBase64(, .stringly)
		_ = .WriteByte('"')
	case SLICE:
		appendValueSliceValue(, .slice)
	case MAP:
		appendMapValue(, .slice)
	case EMPTY:
		_, _ = .WriteString("null")
	default:
		appendJSONString(, "unknown")
	}
}

// appendJSONString appends s to dst as a JSON string literal.
//
// This is adapted from the Go standard library's encoding/json
// [appendString implementation]. It keeps the same escaping behavior we need
// here, but writes directly into a strings.Builder and intentionally does not
// apply HTML escaping because the OpenTelemetry non-OTLP AnyValue representation
// only requires JSON array string encoding. We inline this instead of using
// encoding/json so slice formatting avoids allocations and reflection.
//
// [appendString implementation]: https://github.com/golang/go/blob/3b5954c6349d31465dca409b45ab6597e0942d9f/src/encoding/json/encode.go#L998-L1064
func ( *strings.Builder,  string) {
	const  = "0123456789abcdef" // For escaping bytes to hex.

	_ = .WriteByte('"')
	 := 0

	for  := 0;  < len(); {
		if  := [];  < utf8.RuneSelf {
			if  >= 0x20 &&  != '\\' &&  != '"' {
				++
				continue
			}

			if  <  {
				_, _ = .WriteString([:])
			}

			switch  {
			case '\\', '"':
				_ = .WriteByte('\\')
				_ = .WriteByte()
			case '\b':
				_, _ = .WriteString(`\b`)
			case '\f':
				_, _ = .WriteString(`\f`)
			case '\n':
				_, _ = .WriteString(`\n`)
			case '\r':
				_, _ = .WriteString(`\r`)
			case '\t':
				_, _ = .WriteString(`\t`)
			default:
				_, _ = .WriteString(`\u00`)
				_ = .WriteByte([>>4])
				_ = .WriteByte([&0x0f])
			}

			++
			 = 
			continue
		}

		,  := utf8.DecodeRuneInString([:])
		if  == utf8.RuneError &&  == 1 {
			if  <  {
				_, _ = .WriteString([:])
			}
			// Match encoding/json by replacing invalid UTF-8 with U+FFFD.
			_, _ = .WriteString(`\ufffd`)
			++
			 = 
			continue
		}

		if  == '\u2028' ||  == '\u2029' {
			if  <  {
				_, _ = .WriteString([:])
			}
			// Escape JSONP-sensitive separators unconditionally, like encoding/json.
			_, _ = .WriteString(`\u202`)
			_ = .WriteByte([&0x0f])
			 += 
			 = 
			continue
		}

		 += 
	}

	if  < len() {
		_, _ = .WriteString([:])
	}
	_ = .WriteByte('"')
}

// This is adapted from the Go standard library's encoding/base64
// [Encoding.Encode implementation]. It keeps the same encoding behavior we need
// here, but writes directly into a strings.Builder. We inline this instead of using
// encoding/base64 to avoid allocations.
//
// [Encoding.Encode implementation]: https://github.com/golang/go/blob/3b5954c6349d31465dca409b45ab6597e0942d9f/src/encoding/base64/base64.go#L139-L189
func ( *strings.Builder,  string) {
	const  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

	.Grow(base64.StdEncoding.EncodedLen(len()))

	 := 0
	for ; +2 < len();  += 3 {
		 := uint32([])<<16 | uint32([+1])<<8 | uint32([+2])
		_ = .WriteByte([>>18&0x3f])
		_ = .WriteByte([>>12&0x3f])
		_ = .WriteByte([>>6&0x3f])
		_ = .WriteByte([&0x3f])
	}

	switch len() -  {
	case 1:
		 := uint32([]) << 16
		_ = .WriteByte([>>18&0x3f])
		_ = .WriteByte([>>12&0x3f])
		_ = .WriteByte('=')
		_ = .WriteByte('=')
	case 2:
		 := uint32([])<<16 | uint32([+1])<<8
		_ = .WriteByte([>>18&0x3f])
		_ = .WriteByte([>>12&0x3f])
		_ = .WriteByte([>>6&0x3f])
		_ = .WriteByte('=')
	}
}

// MarshalJSON returns the JSON encoding of the Value.
func ( Value) () ([]byte, error) {
	var  struct {
		  string
		 any
	}
	. = .Type().String()
	. = .AsInterface()
	return json.Marshal()
}