// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT

package extension

import (
	
)

// ConnectionID is a DTLS extension that provides an alternative to IP address
// and port for session association.
//
// https://tools.ietf.org/html/rfc9146
type ConnectionID struct {
	// A zero-length connection ID indicates for a client or server that
	// negotiated connection IDs from the peer will be sent but there is no need
	// to respond with one
	CID []byte // variable length
}

// TypeValue returns the extension TypeValue.
func ( ConnectionID) () TypeValue {
	return ConnectionIDTypeValue
}

// Marshal encodes the extension.
func ( *ConnectionID) () ([]byte, error) {
	var  cryptobyte.Builder
	.AddUint16(uint16(.TypeValue()))
	.AddUint16LengthPrefixed(func( *cryptobyte.Builder) {
		.AddUint8LengthPrefixed(func( *cryptobyte.Builder) {
			.AddBytes(.CID)
		})
	})

	return .Bytes()
}

// Unmarshal populates the extension from encoded data.
func ( *ConnectionID) ( []byte) error {
	 := cryptobyte.String()
	var  uint16
	.ReadUint16(&)
	if TypeValue() != .TypeValue() {
		return errInvalidExtensionType
	}

	var  cryptobyte.String
	.ReadUint16LengthPrefixed(&)

	var  cryptobyte.String
	if !.ReadUint8LengthPrefixed(&) {
		return errInvalidCIDFormat
	}
	.CID = make([]byte, len())
	if !.CopyBytes(.CID) {
		return errInvalidCIDFormat
	}

	return nil
}