Expand description

Derive macros for traits in tls_codec


The derive macros support deriving the tls_codec traits for enumerations and the resulting serialized format complies with the “variants” section of the TLS RFC. However support is limited to enumerations that are serialized with their discriminant immediately followed by the variant data. If this is not appropriate (e.g. the format requires other fields between the discriminant and variant data), the tls_codec traits can be implemented manually.

Available attributes


#[tls_codec(with = "prefix")]

This attribute may be applied to a struct field. It indicates that deriving any of the tls_codec traits for the containing struct calls the following functions:

  • prefix::tls_deserialize when deriving Deserialize
  • prefix::tls_serialize when deriving Serialize
  • prefix::tls_serialized_len when deriving Size

prefix can be a path to a module, type or trait where the functions are defined.

Their expected signatures match the corresponding methods in the traits.

use tls_codec_derive::{TlsSerialize, TlsSize};

#[derive(TlsSerialize, TlsSize)]
struct Bytes {
    #[tls_codec(with = "bytes")]
    values: Vec<u8>,

mod bytes {
    use std::io::Write;
    use tls_codec::{Serialize, Size, TlsByteSliceU32};

    pub fn tls_serialized_len(v: &[u8]) -> usize {

    pub fn tls_serialize<W: Write>(v: &[u8], writer: &mut W) -> Result<usize, tls_codec::Error> {


#[tls_codec(discriminant = 123)]

This attribute may be applied to an enum variant to specify the discriminant to use when serializing it. If all variants are units (e.g. they do not have any data), this attribute must not be used and the desired discriminants should be assigned to the variants using standard Rust syntax (Variant = Discriminant).

For enumerations with non-unit variants, if no variant has this attribute, the serialization discriminants will start from zero. If this attribute is used on a variant and the following variant does not have it, its discriminant will be equal to the previous variant discriminant plus 1.

use tls_codec_derive::{TlsSerialize, TlsSize};

#[derive(TlsSerialize, TlsSize)]
enum Token {
    #[tls_codec(discriminant = 5)]
    Bytes([u8; 16]),

Derive Macros