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

package propagation // import "go.opentelemetry.io/otel/propagation"

import (
	
	
	
	

	
)

const (
	supportedVersion  = 0
	maxVersion        = 254
	traceparentHeader = "traceparent"
	tracestateHeader  = "tracestate"
	delimiter         = "-"
)

// TraceContext is a propagator that supports the W3C Trace Context format
// (https://www.w3.org/TR/trace-context/)
//
// This propagator will propagate the traceparent and tracestate headers to
// guarantee traces are not broken. It is up to the users of this propagator
// to choose if they want to participate in a trace by modifying the
// traceparent header and relevant parts of the tracestate header containing
// their proprietary information.
type TraceContext struct{}

var (
	_           TextMapPropagator = TraceContext{}
	versionPart                   = fmt.Sprintf("%.2X", supportedVersion)
)

// Inject injects the trace context from ctx into carrier.
func (TraceContext) ( context.Context,  TextMapCarrier) {
	 := trace.SpanContextFromContext()
	if !.IsValid() {
		return
	}

	if  := .TraceState().String();  != "" {
		.Set(tracestateHeader, )
	}

	// Clear all flags other than the trace-context supported sampling bit.
	 := .TraceFlags() & trace.FlagsSampled

	var  strings.Builder
	.Grow(2 + 32 + 16 + 2 + 3)
	_, _ = .WriteString(versionPart)
	 := .TraceID()
	 := .SpanID()
	 := [1]byte{byte()}
	var  [32]byte
	for ,  := range [][]byte{[:], [:], [:]} {
		_ = .WriteByte(delimiter[0])
		 := hex.Encode([:], )
		_, _ = .Write([:])
	}
	.Set(traceparentHeader, .String())
}

// Extract reads tracecontext from the carrier into a returned Context.
//
// The returned Context will be a copy of ctx and contain the extracted
// tracecontext as the remote SpanContext. If the extracted tracecontext is
// invalid, the passed ctx will be returned directly instead.
func ( TraceContext) ( context.Context,  TextMapCarrier) context.Context {
	 := .extract()
	if !.IsValid() {
		return 
	}
	return trace.ContextWithRemoteSpanContext(, )
}

func (TraceContext) ( TextMapCarrier) trace.SpanContext {
	 := .Get(traceparentHeader)
	if  == "" {
		return trace.SpanContext{}
	}

	var  [1]byte
	if !extractPart([:], &, 2) {
		return trace.SpanContext{}
	}
	 := int([0])
	if  > maxVersion {
		return trace.SpanContext{}
	}

	var  trace.SpanContextConfig
	if !extractPart(.TraceID[:], &, 32) {
		return trace.SpanContext{}
	}
	if !extractPart(.SpanID[:], &, 16) {
		return trace.SpanContext{}
	}

	var  [1]byte
	if !extractPart([:], &, 2) {
		return trace.SpanContext{}
	}
	if  == 0 && ( != "" || [0] > 2) {
		// version 0 not allow extra
		// version 0 not allow other flag
		return trace.SpanContext{}
	}

	// Clear all flags other than the trace-context supported sampling bit.
	.TraceFlags = trace.TraceFlags([0]) & trace.FlagsSampled

	// Ignore the error returned here. Failure to parse tracestate MUST NOT
	// affect the parsing of traceparent according to the W3C tracecontext
	// specification.
	.TraceState, _ = trace.ParseTraceState(.Get(tracestateHeader))
	.Remote = true

	 := trace.NewSpanContext()
	if !.IsValid() {
		return trace.SpanContext{}
	}

	return 
}

// upperHex detect hex is upper case Unicode characters.
func upperHex( string) bool {
	for ,  := range  {
		if  >= 'A' &&  <= 'F' {
			return true
		}
	}
	return false
}

func extractPart( []byte,  *string,  int) bool {
	, ,  := strings.Cut(*, delimiter)
	* = 
	// hex.Decode decodes unsupported upper-case characters, so exclude explicitly.
	if len() !=  || upperHex() {
		return false
	}
	if ,  := hex.Decode(, []byte());  != nil ||  != /2 {
		return false
	}
	return true
}

// Fields returns the keys who's values are set with Inject.
func (TraceContext) () []string {
	return []string{traceparentHeader, tracestateHeader}
}