// 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{
		mu:            &sync.RWMutex{},
		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 {
			h.agreementPartyUInfo = v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, AgreementPartyUInfoKey, value)
	case AgreementPartyVInfoKey:
		if v, ok := value.([]byte); ok {
			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 {
			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.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); 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); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, JWKSetURLKey, err)
				}
			case KeyIDKey:
				if err := json.AssignNextStringToken(&h.keyID, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyIDKey, err)
				}
			case TypeKey:
				if err := json.AssignNextStringToken(&h.typ, dec); 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); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintKey, err)
				}
			case X509CertThumbprintS256Key:
				if err := json.AssignNextStringToken(&h.x509CertThumbprintS256, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintS256Key, err)
				}
			case X509URLKey:
				if err := json.AssignNextStringToken(&h.x509URL, dec); 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
}

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

	sort.Strings(keys)
	buf := pool.BytesBuffer().Get()
	defer pool.BytesBuffer().Put(buf)
	enc := json.NewEncoder(buf)
	buf.WriteByte(tokens.OpenCurlyBracket)
	for i, k := range keys {
		if i > 0 {
			buf.WriteRune(tokens.Comma)
		}
		buf.WriteRune(tokens.DoubleQuote)
		buf.WriteString(k)
		buf.WriteString(`":`)
		v := data[k]
		switch v := v.(type) {
		case []byte:
			buf.WriteRune(tokens.DoubleQuote)
			buf.WriteString(base64.EncodeToString(v))
			buf.WriteRune(tokens.DoubleQuote)
		default:
			if err := enc.Encode(v); err != nil {
				return nil, fmt.Errorf(`failed to encode value for field %s`, k)
			}
			buf.Truncate(buf.Len() - 1)
		}
	}
	buf.WriteByte(tokens.CloseCurlyBracket)
	ret := make([]byte, buf.Len())
	copy(ret, buf.Bytes())
	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
	h.privateParams = map[string]any{}
	h.mu.Unlock()
}
