package faketls

import (
	
	
	

	
)

const maxTLSRecordDataLength = 16384 + 24

type record struct {
	Type    RecordType
	Version [2]byte
	Data    []byte
}

func ( io.Reader) (record, error) {
	 := record{}

	 := make([]byte, 5)
	if ,  := io.ReadFull(, );  != nil {
		return record{}, 
	}

	.Type = RecordType([0])
	 := [1:3]
	switch {
	case bytes.Equal(, Version13Bytes[:]):
		.Version = Version13Bytes
	case bytes.Equal(, Version12Bytes[:]):
		.Version = Version12Bytes
	case bytes.Equal(, Version11Bytes[:]):
		.Version = Version11Bytes
	case bytes.Equal(, Version10Bytes[:]):
		.Version = Version10Bytes
	default:
		return record{}, errors.Errorf("unknown protocol version %v", )
	}

	 := binary.BigEndian.Uint16([3:])
	if  > maxTLSRecordDataLength {
		return record{}, errors.New("record length is too big")
	}

	.Data = make([]byte, )
	if ,  := io.ReadFull(, .Data);  != nil {
		return record{}, 
	}

	return , nil
}

func ( io.Writer,  record) (int, error) {
	 := [...]byte{
		byte(.Type),
		.Version[0], .Version[1],
	}

	if ,  := .Write([:]);  != nil {
		return 0, errors.Wrap(, "type and version")
	}

	binary.BigEndian.PutUint16([:2], uint16(len(.Data)))
	if ,  := .Write([:2]);  != nil {
		return 0, errors.Wrap(, "data length")
	}

	,  := .Write(.Data)
	if  != nil {
		return 0, errors.Wrap(, "data")
	}

	return , nil
}