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

package jws

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 (
	AlgorithmKey              = "alg"
	B64Key                    = "b64"
	ContentTypeKey            = "cty"
	CriticalKey               = "crit"
	JWKKey                    = "jwk"
	JWKSetURLKey              = "jku"
	KeyIDKey                  = "kid"
	TypeKey                   = "typ"
	X509CertChainKey          = "x5c"
	X509CertThumbprintKey     = "x5t"
	X509CertThumbprintS256Key = "x5t#S256"
	X509URLKey                = "x5u"
)

// Headers describe a standard JWS Header set. It is part of the JWS message
// and is used to represet both Public or Protected headers, which in turn
// can be found in each Signature object. If you are not sure how this works,
// it is strongly recommended that you read RFC7515, especially the section
// that describes the full JSON serialization format of JWS messages.
//
// In most cases, you likely want to use the protected headers, as this is part of the signed content.
type Headers interface {
	Algorithm() (jwa.SignatureAlgorithm, bool)
	B64() (bool, bool)
	ContentType() (string, bool)
	Critical() ([]string, 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)
	Copy(Headers) error
	Merge(Headers) (Headers, error)
	Clone() (Headers, error)
	// 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
	Keys() []string
}

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

type stdHeaders struct {
	algorithm              *jwa.SignatureAlgorithm // https://tools.ietf.org/html/rfc7515#section-4.1.1
	b64                    *bool                   // https://tools.ietf.org/html/rfc7797#section-3
	contentType            *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.10
	critical               []string                // https://tools.ietf.org/html/rfc7515#section-4.1.11
	jwk                    jwk.Key                 // https://tools.ietf.org/html/rfc7515#section-4.1.3
	jwkSetURL              *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.2
	keyID                  *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.4
	typ                    *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.9
	x509CertChain          *cert.Chain             // https://tools.ietf.org/html/rfc7515#section-4.1.6
	x509CertThumbprint     *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.7
	x509CertThumbprintS256 *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.8
	x509URL                *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.5
	privateParams          map[string]any
	mu                     sync.RWMutex
	dc                     DecodeCtx
	raw                    []byte // stores the raw version of the header so it can be used later
}

func NewHeaders() Headers {
	return &stdHeaders{}
}

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

func (h *stdHeaders) B64() (bool, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.b64 == nil {
		return false, false
	}
	return *(h.b64), 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) 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) clear() {
	h.algorithm = nil
	h.b64 = nil
	h.contentType = nil
	h.critical = 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 = nil
	h.raw = nil
}

func (h *stdHeaders) DecodeCtx() DecodeCtx {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.dc
}

func (h *stdHeaders) SetDecodeCtx(dc DecodeCtx) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.dc = dc
}

func (h *stdHeaders) rawBuffer() []byte {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.raw
}

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 AlgorithmKey:
		return h.algorithm != nil
	case B64Key:
		return h.b64 != nil
	case ContentTypeKey:
		return h.contentType != nil
	case CriticalKey:
		return h.critical != 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 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)
		}
		return nil
	case B64Key:
		if h.b64 == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.b64)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	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)
		}
		return nil
	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)
		}
		return nil
	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)
		}
		return nil
	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)
		}
		return nil
	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)
		}
		return nil
	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)
		}
		return nil
	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)
		}
		return nil
	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)
		}
		return nil
	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)
		}
		return nil
	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)
		}
		return nil
	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 AlgorithmKey:
		alg, err := jwa.KeyAlgorithmFrom(value)
		if err != nil {
			return fmt.Errorf("invalid value for %s key: %w", AlgorithmKey, err)
		}
		if salg, ok := alg.(jwa.SignatureAlgorithm); ok {
			h.algorithm = &salg
			return nil
		}
		return fmt.Errorf("expecte jwa.SignatureAlgorithm, received %T", alg)
	case B64Key:
		if v, ok := value.(bool); ok {
			h.b64 = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, B64Key, 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 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 AlgorithmKey:
		h.algorithm = nil
	case B64Key:
		h.b64 = nil
	case ContentTypeKey:
		h.contentType = nil
	case CriticalKey:
		h.critical = 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.clear()
	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 AlgorithmKey:
				var decoded jwa.SignatureAlgorithm
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, AlgorithmKey, err)
				}
				h.algorithm = &decoded
			case B64Key:
				var decoded bool
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, B64Key, err)
				}
				h.b64 = &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 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)
		}
	}
	h.raw = buf
	return nil
}

func (h *stdHeaders) Keys() []string {
	h.mu.RLock()
	defer h.mu.RUnlock()
	keys := make([]string, 0, 12+len(h.privateParams))
	if h.algorithm != nil {
		keys = append(keys, AlgorithmKey)
	}
	if h.b64 != nil {
		keys = append(keys, B64Key)
	}
	if h.contentType != nil {
		keys = append(keys, ContentTypeKey)
	}
	if h.critical != nil {
		keys = append(keys, CriticalKey)
	}
	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, 12)
	},
}

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.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.b64 != nil {
		v, err := json.Marshal(*(h.b64))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, B64Key, err)
		}
		pairs = append(pairs, headerPair{Name: B64Key, 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.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
}
