// Code generated by tools/cmd/genjwe/main.go. DO NOT EDIT.

package jwe

import (
	"bytes"
	"fmt"
	"sort"
	"sync"

	"github.com/lestrrat-go/blackmagic"
	"github.com/lestrrat-go/jwx/v3/cert"
	"github.com/lestrrat-go/jwx/v3/internal/base64"
	"github.com/lestrrat-go/jwx/v3/internal/json"
	"github.com/lestrrat-go/jwx/v3/internal/pool"
	"github.com/lestrrat-go/jwx/v3/internal/tokens"
	"github.com/lestrrat-go/jwx/v3/jwa"
	"github.com/lestrrat-go/jwx/v3/jwk"
)

const (
	AgreementPartyUInfoKey    = "apu"
	AgreementPartyVInfoKey    = "apv"
	AlgorithmKey              = "alg"
	CompressionKey            = "zip"
	ContentEncryptionKey      = "enc"
	ContentTypeKey            = "cty"
	CriticalKey               = "crit"
	EphemeralPublicKeyKey     = "epk"
	JWKKey                    = "jwk"
	JWKSetURLKey              = "jku"
	KeyIDKey                  = "kid"
	TypeKey                   = "typ"
	X509CertChainKey          = "x5c"
	X509CertThumbprintKey     = "x5t"
	X509CertThumbprintS256Key = "x5t#S256"
	X509URLKey                = "x5u"
)

// Headers describe a standard JWE Header set. It is part of the JWE message
// and is used to represent both Protected and Unprotected headers,
// which in turn can be found in each Recipient object.
// If you are not sure how this works, it is strongly recommended that
// you read RFC7516, especially the section
// that describes the full JSON serialization format of JWE messages.
//
// In most cases, you likely want to use the protected headers, as this is the part of the encrypted content
type Headers interface {
	AgreementPartyUInfo() ([]byte, bool)
	AgreementPartyVInfo() ([]byte, bool)
	Algorithm() (jwa.KeyEncryptionAlgorithm, bool)
	Compression() (jwa.CompressionAlgorithm, bool)
	ContentEncryption() (jwa.ContentEncryptionAlgorithm, bool)
	ContentType() (string, bool)
	Critical() ([]string, bool)
	EphemeralPublicKey() (jwk.Key, bool)
	JWK() (jwk.Key, bool)
	JWKSetURL() (string, bool)
	KeyID() (string, bool)
	Type() (string, bool)
	X509CertChain() (*cert.Chain, bool)
	X509CertThumbprint() (string, bool)
	X509CertThumbprintS256() (string, bool)
	X509URL() (string, bool)

	// Get is used to extract the value of any field, including non-standard fields, out of the header.
	//
	// The first argument is the name of the field. The second argument is a pointer
	// to a variable that will receive the value of the field. The method returns
	// an error if the field does not exist, or if the value cannot be assigned to
	// the destination variable. Note that a field is considered to "exist" even if
	// the value is empty-ish (e.g. 0, false, ""), as long as it is explicitly set.
	Get(string, any) error
	Set(string, any) error
	Remove(string) error
	// Has returns true if the specified header has a value, even if
	// the value is empty-ish (e.g. 0, false, "")  as long as it has been
	// explicitly set.
	Has(string) bool
	Encode() ([]byte, error)
	Decode([]byte) error
	Clone() (Headers, error)
	Copy(Headers) error
	Merge(Headers) (Headers, error)

	// Keys returns a list of the keys contained in this header.
	Keys() []string
}

// stdHeaderNames is a list of all standard header names defined in the JWE specification.
var stdHeaderNames = []string{AgreementPartyUInfoKey, AgreementPartyVInfoKey, AlgorithmKey, CompressionKey, ContentEncryptionKey, ContentTypeKey, CriticalKey, EphemeralPublicKeyKey, JWKKey, JWKSetURLKey, KeyIDKey, TypeKey, X509CertChainKey, X509CertThumbprintKey, X509CertThumbprintS256Key, X509URLKey}

type stdHeaders struct {
	agreementPartyUInfo    []byte
	agreementPartyVInfo    []byte
	algorithm              *jwa.KeyEncryptionAlgorithm
	compression            *jwa.CompressionAlgorithm
	contentEncryption      *jwa.ContentEncryptionAlgorithm
	contentType            *string
	critical               []string
	ephemeralPublicKey     jwk.Key
	jwk                    jwk.Key
	jwkSetURL              *string
	keyID                  *string
	typ                    *string
	x509CertChain          *cert.Chain
	x509CertThumbprint     *string
	x509CertThumbprintS256 *string
	x509URL                *string
	privateParams          map[string]any
	mu                     sync.RWMutex
}

func NewHeaders() Headers {
	return &stdHeaders{
		privateParams: map[string]any{},
	}
}

func (h *stdHeaders) AgreementPartyUInfo() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.agreementPartyUInfo, h.agreementPartyUInfo != nil
}

func (h *stdHeaders) AgreementPartyVInfo() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.agreementPartyVInfo, h.agreementPartyVInfo != nil
}

func (h *stdHeaders) Algorithm() (jwa.KeyEncryptionAlgorithm, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.algorithm == nil {
		return jwa.EmptyKeyEncryptionAlgorithm(), false
	}
	return *(h.algorithm), true
}

func (h *stdHeaders) Compression() (jwa.CompressionAlgorithm, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.compression == nil {
		return jwa.NoCompress(), false
	}
	return *(h.compression), true
}

func (h *stdHeaders) ContentEncryption() (jwa.ContentEncryptionAlgorithm, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.contentEncryption == nil {
		return jwa.EmptyContentEncryptionAlgorithm(), false
	}
	return *(h.contentEncryption), true
}

func (h *stdHeaders) ContentType() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.contentType == nil {
		return "", false
	}
	return *(h.contentType), true
}

func (h *stdHeaders) Critical() ([]string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.critical, h.critical != nil
}

func (h *stdHeaders) EphemeralPublicKey() (jwk.Key, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.ephemeralPublicKey, h.ephemeralPublicKey != nil
}

func (h *stdHeaders) JWK() (jwk.Key, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.jwk, h.jwk != nil
}

func (h *stdHeaders) JWKSetURL() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.jwkSetURL == nil {
		return "", false
	}
	return *(h.jwkSetURL), true
}

func (h *stdHeaders) KeyID() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.keyID == nil {
		return "", false
	}
	return *(h.keyID), true
}

func (h *stdHeaders) Type() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.typ == nil {
		return "", false
	}
	return *(h.typ), true
}

func (h *stdHeaders) X509CertChain() (*cert.Chain, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.x509CertChain, h.x509CertChain != nil
}

func (h *stdHeaders) X509CertThumbprint() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509CertThumbprint == nil {
		return "", false
	}
	return *(h.x509CertThumbprint), true
}

func (h *stdHeaders) X509CertThumbprintS256() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509CertThumbprintS256 == nil {
		return "", false
	}
	return *(h.x509CertThumbprintS256), true
}

func (h *stdHeaders) X509URL() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509URL == nil {
		return "", false
	}
	return *(h.x509URL), true
}

func (h *stdHeaders) PrivateParams() map[string]any {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.privateParams
}

func (h *stdHeaders) Has(name string) bool {
	h.mu.RLock()
	defer h.mu.RUnlock()
	switch name {
	case AgreementPartyUInfoKey:
		return h.agreementPartyUInfo != nil
	case AgreementPartyVInfoKey:
		return h.agreementPartyVInfo != nil
	case AlgorithmKey:
		return h.algorithm != nil
	case CompressionKey:
		return h.compression != nil
	case ContentEncryptionKey:
		return h.contentEncryption != nil
	case ContentTypeKey:
		return h.contentType != nil
	case CriticalKey:
		return h.critical != nil
	case EphemeralPublicKeyKey:
		return h.ephemeralPublicKey != nil
	case JWKKey:
		return h.jwk != nil
	case JWKSetURLKey:
		return h.jwkSetURL != nil
	case KeyIDKey:
		return h.keyID != nil
	case TypeKey:
		return h.typ != nil
	case X509CertChainKey:
		return h.x509CertChain != nil
	case X509CertThumbprintKey:
		return h.x509CertThumbprint != nil
	case X509CertThumbprintS256Key:
		return h.x509CertThumbprintS256 != nil
	case X509URLKey:
		return h.x509URL != nil
	default:
		_, ok := h.privateParams[name]
		return ok
	}
}

func (h *stdHeaders) Get(name string, dst any) error {
	h.mu.RLock()
	defer h.mu.RUnlock()
	switch name {
	case AgreementPartyUInfoKey:
		if h.agreementPartyUInfo == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.agreementPartyUInfo); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case AgreementPartyVInfoKey:
		if h.agreementPartyVInfo == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.agreementPartyVInfo); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case AlgorithmKey:
		if h.algorithm == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.algorithm)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case CompressionKey:
		if h.compression == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.compression)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case ContentEncryptionKey:
		if h.contentEncryption == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.contentEncryption)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case ContentTypeKey:
		if h.contentType == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.contentType)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case CriticalKey:
		if h.critical == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.critical); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case EphemeralPublicKeyKey:
		if h.ephemeralPublicKey == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.ephemeralPublicKey); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case JWKKey:
		if h.jwk == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.jwk); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case JWKSetURLKey:
		if h.jwkSetURL == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.jwkSetURL)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case KeyIDKey:
		if h.keyID == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.keyID)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case TypeKey:
		if h.typ == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.typ)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case X509CertChainKey:
		if h.x509CertChain == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.x509CertChain); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case X509CertThumbprintKey:
		if h.x509CertThumbprint == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509CertThumbprint)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case X509CertThumbprintS256Key:
		if h.x509CertThumbprintS256 == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509CertThumbprintS256)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	case X509URLKey:
		if h.x509URL == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509URL)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	default:
		v, ok := h.privateParams[name]
		if !ok {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, v); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	}
	return nil
}

func (h *stdHeaders) Set(name string, value any) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	return h.setNoLock(name, value)
}

func (h *stdHeaders) setNoLock(name string, value any) error {
	switch name {
	case AgreementPartyUInfoKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.agreementPartyUInfo = nil
			} else {
				h.agreementPartyUInfo = make([]byte, len(v))
				copy(h.agreementPartyUInfo, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, AgreementPartyUInfoKey, value)
	case AgreementPartyVInfoKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.agreementPartyVInfo = nil
			} else {
				h.agreementPartyVInfo = make([]byte, len(v))
				copy(h.agreementPartyVInfo, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, AgreementPartyVInfoKey, value)
	case AlgorithmKey:
		if v, ok := value.(jwa.KeyEncryptionAlgorithm); ok {
			h.algorithm = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, AlgorithmKey, value)
	case CompressionKey:
		if v, ok := value.(jwa.CompressionAlgorithm); ok {
			h.compression = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, CompressionKey, value)
	case ContentEncryptionKey:
		if v, ok := value.(jwa.ContentEncryptionAlgorithm); ok {
			if v == jwa.EmptyContentEncryptionAlgorithm() {
				return fmt.Errorf(`"enc" field cannot be an empty string`)
			}
			h.contentEncryption = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, ContentEncryptionKey, value)
	case ContentTypeKey:
		if v, ok := value.(string); ok {
			h.contentType = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, ContentTypeKey, value)
	case CriticalKey:
		if v, ok := value.([]string); ok {
			if v == nil {
				h.critical = nil
			} else {
				h.critical = make([]string, len(v))
				copy(h.critical, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, CriticalKey, value)
	case EphemeralPublicKeyKey:
		if v, ok := value.(jwk.Key); ok {
			h.ephemeralPublicKey = v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, EphemeralPublicKeyKey, value)
	case JWKKey:
		if v, ok := value.(jwk.Key); ok {
			h.jwk = v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, JWKKey, value)
	case JWKSetURLKey:
		if v, ok := value.(string); ok {
			h.jwkSetURL = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, JWKSetURLKey, value)
	case KeyIDKey:
		if v, ok := value.(string); ok {
			h.keyID = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, KeyIDKey, value)
	case TypeKey:
		if v, ok := value.(string); ok {
			h.typ = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, TypeKey, value)
	case X509CertChainKey:
		if v, ok := value.(*cert.Chain); ok {
			h.x509CertChain = v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertChainKey, value)
	case X509CertThumbprintKey:
		if v, ok := value.(string); ok {
			h.x509CertThumbprint = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintKey, value)
	case X509CertThumbprintS256Key:
		if v, ok := value.(string); ok {
			h.x509CertThumbprintS256 = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintS256Key, value)
	case X509URLKey:
		if v, ok := value.(string); ok {
			h.x509URL = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509URLKey, value)
	default:
		if h.privateParams == nil {
			h.privateParams = map[string]any{}
		}
		h.privateParams[name] = value
	}
	return nil
}

func (h *stdHeaders) Remove(key string) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	switch key {
	case AgreementPartyUInfoKey:
		h.agreementPartyUInfo = nil
	case AgreementPartyVInfoKey:
		h.agreementPartyVInfo = nil
	case AlgorithmKey:
		h.algorithm = nil
	case CompressionKey:
		h.compression = nil
	case ContentEncryptionKey:
		h.contentEncryption = nil
	case ContentTypeKey:
		h.contentType = nil
	case CriticalKey:
		h.critical = nil
	case EphemeralPublicKeyKey:
		h.ephemeralPublicKey = nil
	case JWKKey:
		h.jwk = nil
	case JWKSetURLKey:
		h.jwkSetURL = nil
	case KeyIDKey:
		h.keyID = nil
	case TypeKey:
		h.typ = nil
	case X509CertChainKey:
		h.x509CertChain = nil
	case X509CertThumbprintKey:
		h.x509CertThumbprint = nil
	case X509CertThumbprintS256Key:
		h.x509CertThumbprintS256 = nil
	case X509URLKey:
		h.x509URL = nil
	default:
		delete(h.privateParams, key)
	}
	return nil
}

func (h *stdHeaders) UnmarshalJSON(buf []byte) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.agreementPartyUInfo = nil
	h.agreementPartyVInfo = nil
	h.algorithm = nil
	h.compression = nil
	h.contentEncryption = nil
	h.contentType = nil
	h.critical = nil
	h.ephemeralPublicKey = nil
	h.jwk = nil
	h.jwkSetURL = nil
	h.keyID = nil
	h.typ = nil
	h.x509CertChain = nil
	h.x509CertThumbprint = nil
	h.x509CertThumbprintS256 = nil
	h.x509URL = nil
	dec := json.NewDecoder(bytes.NewReader(buf))
LOOP:
	for {
		tok, err := dec.Token()
		if err != nil {
			return fmt.Errorf(`error reading token: %w`, err)
		}
		switch tok := tok.(type) {
		case json.Delim:
			// Assuming we're doing everything correctly, we should ONLY
			// get either tokens.OpenCurlyBracket or tokens.CloseCurlyBracket here.
			if tok == tokens.CloseCurlyBracket { // End of object
				break LOOP
			} else if tok != tokens.OpenCurlyBracket {
				return fmt.Errorf(`expected '%c' but got '%c'`, tokens.OpenCurlyBracket, tok)
			}
		case string: // Objects can only have string keys
			switch tok {
			case AgreementPartyUInfoKey:
				if err := json.AssignNextBytesToken(&h.agreementPartyUInfo, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, AgreementPartyUInfoKey, err)
				}
			case AgreementPartyVInfoKey:
				if err := json.AssignNextBytesToken(&h.agreementPartyVInfo, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, AgreementPartyVInfoKey, err)
				}
			case AlgorithmKey:
				var decoded jwa.KeyEncryptionAlgorithm
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, AlgorithmKey, err)
				}
				h.algorithm = &decoded
			case CompressionKey:
				var decoded jwa.CompressionAlgorithm
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, CompressionKey, err)
				}
				h.compression = &decoded
			case ContentEncryptionKey:
				var decoded jwa.ContentEncryptionAlgorithm
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, ContentEncryptionKey, err)
				}
				h.contentEncryption = &decoded
			case ContentTypeKey:
				if err := json.AssignNextStringToken(&h.contentType, dec, nil); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, ContentTypeKey, err)
				}
			case CriticalKey:
				var decoded []string
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, CriticalKey, err)
				}
				h.critical = decoded
			case EphemeralPublicKeyKey:
				var buf json.RawMessage
				if err := dec.Decode(&buf); err != nil {
					return fmt.Errorf(`failed to decode value for key %s:%w`, EphemeralPublicKeyKey, err)
				}
				key, err := jwk.ParseKey(buf)
				if err != nil {
					return fmt.Errorf(`failed to parse JWK for key %s: %w`, EphemeralPublicKeyKey, err)
				}
				h.ephemeralPublicKey = key
			case JWKKey:
				var buf json.RawMessage
				if err := dec.Decode(&buf); err != nil {
					return fmt.Errorf(`failed to decode value for key %s:%w`, JWKKey, err)
				}
				key, err := jwk.ParseKey(buf)
				if err != nil {
					return fmt.Errorf(`failed to parse JWK for key %s: %w`, JWKKey, err)
				}
				h.jwk = key
			case JWKSetURLKey:
				if err := json.AssignNextStringToken(&h.jwkSetURL, dec, nil); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, JWKSetURLKey, err)
				}
			case KeyIDKey:
				if err := json.AssignNextStringToken(&h.keyID, dec, nil); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyIDKey, err)
				}
			case TypeKey:
				if err := json.AssignNextStringToken(&h.typ, dec, nil); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, TypeKey, err)
				}
			case X509CertChainKey:
				var decoded cert.Chain
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertChainKey, err)
				}
				h.x509CertChain = &decoded
			case X509CertThumbprintKey:
				if err := json.AssignNextStringToken(&h.x509CertThumbprint, dec, nil); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintKey, err)
				}
			case X509CertThumbprintS256Key:
				if err := json.AssignNextStringToken(&h.x509CertThumbprintS256, dec, nil); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintS256Key, err)
				}
			case X509URLKey:
				if err := json.AssignNextStringToken(&h.x509URL, dec, nil); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509URLKey, err)
				}
			default:
				decoded, err := registry.Decode(dec, tok)
				if err != nil {
					return err
				}
				h.setNoLock(tok, decoded)
			}
		default:
			return fmt.Errorf(`invalid token %T`, tok)
		}
	}
	return nil
}

func (h *stdHeaders) Keys() []string {
	h.mu.RLock()
	defer h.mu.RUnlock()
	keys := make([]string, 0, 16+len(h.privateParams))
	if h.agreementPartyUInfo != nil {
		keys = append(keys, AgreementPartyUInfoKey)
	}
	if h.agreementPartyVInfo != nil {
		keys = append(keys, AgreementPartyVInfoKey)
	}
	if h.algorithm != nil {
		keys = append(keys, AlgorithmKey)
	}
	if h.compression != nil {
		keys = append(keys, CompressionKey)
	}
	if h.contentEncryption != nil {
		keys = append(keys, ContentEncryptionKey)
	}
	if h.contentType != nil {
		keys = append(keys, ContentTypeKey)
	}
	if h.critical != nil {
		keys = append(keys, CriticalKey)
	}
	if h.ephemeralPublicKey != nil {
		keys = append(keys, EphemeralPublicKeyKey)
	}
	if h.jwk != nil {
		keys = append(keys, JWKKey)
	}
	if h.jwkSetURL != nil {
		keys = append(keys, JWKSetURLKey)
	}
	if h.keyID != nil {
		keys = append(keys, KeyIDKey)
	}
	if h.typ != nil {
		keys = append(keys, TypeKey)
	}
	if h.x509CertChain != nil {
		keys = append(keys, X509CertChainKey)
	}
	if h.x509CertThumbprint != nil {
		keys = append(keys, X509CertThumbprintKey)
	}
	if h.x509CertThumbprintS256 != nil {
		keys = append(keys, X509CertThumbprintS256Key)
	}
	if h.x509URL != nil {
		keys = append(keys, X509URLKey)
	}
	for k := range h.privateParams {
		keys = append(keys, k)
	}
	return keys
}

type headerPair struct {
	Name  string
	Value any
}

var headerPairPool = sync.Pool{
	New: func() any {
		return make([]headerPair, 0, 16)
	},
}

func getHeaderPairList() []headerPair {
	return headerPairPool.Get().([]headerPair)
}

func putHeaderPairList(list []headerPair) {
	list = list[:0]
	headerPairPool.Put(list)
}

func (h *stdHeaders) makePairs() ([]headerPair, error) {
	pairs := getHeaderPairList()
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.agreementPartyUInfo != nil {
		v, err := json.Marshal(base64.EncodeToString(h.agreementPartyUInfo))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, AgreementPartyUInfoKey, err)
		}
		pairs = append(pairs, headerPair{Name: AgreementPartyUInfoKey, Value: v})
	}
	if h.agreementPartyVInfo != nil {
		v, err := json.Marshal(base64.EncodeToString(h.agreementPartyVInfo))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, AgreementPartyVInfoKey, err)
		}
		pairs = append(pairs, headerPair{Name: AgreementPartyVInfoKey, Value: v})
	}
	if h.algorithm != nil {
		v, err := json.Marshal(*(h.algorithm))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, AlgorithmKey, err)
		}
		pairs = append(pairs, headerPair{Name: AlgorithmKey, Value: v})
	}
	if h.compression != nil {
		v, err := json.Marshal(*(h.compression))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, CompressionKey, err)
		}
		pairs = append(pairs, headerPair{Name: CompressionKey, Value: v})
	}
	if h.contentEncryption != nil {
		v, err := json.Marshal(*(h.contentEncryption))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, ContentEncryptionKey, err)
		}
		pairs = append(pairs, headerPair{Name: ContentEncryptionKey, Value: v})
	}
	if h.contentType != nil {
		v, err := json.Marshal(*(h.contentType))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, ContentTypeKey, err)
		}
		pairs = append(pairs, headerPair{Name: ContentTypeKey, Value: v})
	}
	if h.critical != nil {
		v, err := json.Marshal(h.critical)
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, CriticalKey, err)
		}
		pairs = append(pairs, headerPair{Name: CriticalKey, Value: v})
	}
	if h.ephemeralPublicKey != nil {
		v, err := json.Marshal(h.ephemeralPublicKey)
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, EphemeralPublicKeyKey, err)
		}
		pairs = append(pairs, headerPair{Name: EphemeralPublicKeyKey, Value: v})
	}
	if h.jwk != nil {
		v, err := json.Marshal(h.jwk)
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, JWKKey, err)
		}
		pairs = append(pairs, headerPair{Name: JWKKey, Value: v})
	}
	if h.jwkSetURL != nil {
		v, err := json.Marshal(*(h.jwkSetURL))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, JWKSetURLKey, err)
		}
		pairs = append(pairs, headerPair{Name: JWKSetURLKey, Value: v})
	}
	if h.keyID != nil {
		v, err := json.Marshal(*(h.keyID))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, KeyIDKey, err)
		}
		pairs = append(pairs, headerPair{Name: KeyIDKey, Value: v})
	}
	if h.typ != nil {
		v, err := json.Marshal(*(h.typ))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, TypeKey, err)
		}
		pairs = append(pairs, headerPair{Name: TypeKey, Value: v})
	}
	if h.x509CertChain != nil {
		v, err := json.Marshal(h.x509CertChain)
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509CertChainKey, err)
		}
		pairs = append(pairs, headerPair{Name: X509CertChainKey, Value: v})
	}
	if h.x509CertThumbprint != nil {
		v, err := json.Marshal(*(h.x509CertThumbprint))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509CertThumbprintKey, err)
		}
		pairs = append(pairs, headerPair{Name: X509CertThumbprintKey, Value: v})
	}
	if h.x509CertThumbprintS256 != nil {
		v, err := json.Marshal(*(h.x509CertThumbprintS256))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509CertThumbprintS256Key, err)
		}
		pairs = append(pairs, headerPair{Name: X509CertThumbprintS256Key, Value: v})
	}
	if h.x509URL != nil {
		v, err := json.Marshal(*(h.x509URL))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509URLKey, err)
		}
		pairs = append(pairs, headerPair{Name: X509URLKey, Value: v})
	}
	for k, v := range h.privateParams {
		var encoded []byte
		switch v := v.(type) {
		case []byte:
			var err error
			encoded, err = json.Marshal(base64.EncodeToString(v))
			if err != nil {
				return nil, fmt.Errorf(`failed to marshal field %q: %w`, k, err)
			}
		default:
			var err error
			encoded, err = json.Marshal(v)
			if err != nil {
				return nil, fmt.Errorf(`failed to marshal field %q: %w`, k, err)
			}
		}
		pairs = append(pairs, headerPair{Name: k, Value: encoded})
	}

	sort.Slice(pairs, func(i, j int) bool {
		return pairs[i].Name < pairs[j].Name
	})

	return pairs, nil
}

func (h *stdHeaders) MarshalJSON() ([]byte, error) {
	buf := pool.BytesBuffer().Get()
	defer pool.BytesBuffer().Put(buf)
	pairs, err := h.makePairs()
	if err != nil {
		return nil, fmt.Errorf(`failed to make pairs: %w`, err)
	}
	buf.WriteByte(tokens.OpenCurlyBracket)

	for i, pair := range pairs {
		if i > 0 {
			buf.WriteByte(tokens.Comma)
		}
		buf.WriteByte('"')
		buf.WriteString(pair.Name)
		buf.WriteString(`": `)
		buf.Write(pair.Value.([]byte))
	}
	buf.WriteByte(tokens.CloseCurlyBracket)
	ret := make([]byte, buf.Len())
	copy(ret, buf.Bytes())
	putHeaderPairList(pairs)
	return ret, nil
}

func (h *stdHeaders) clear() {
	h.mu.Lock()
	h.agreementPartyUInfo = nil
	h.agreementPartyVInfo = nil
	h.algorithm = nil
	h.compression = nil
	h.contentEncryption = nil
	h.contentType = nil
	h.critical = nil
	h.ephemeralPublicKey = nil
	h.jwk = nil
	h.jwkSetURL = nil
	h.keyID = nil
	h.typ = nil
	h.x509CertChain = nil
	h.x509CertThumbprint = nil
	h.x509CertThumbprintS256 = nil
	h.x509URL = nil
	clear(h.privateParams)
	h.mu.Unlock()
}
