Skip to main content

Crate cbor2_derive

Crate cbor2_derive 

Source
Expand description

Derive support for protocol-shaped CBOR with cbor2.

This crate provides the implementation behind #[derive(cbor2::Cbor)]. Users normally enable it through the derive feature of the cbor2 crate:

[dependencies]
cbor2 = { version = "1", features = ["derive"] }
serde_bytes = "0.11" # only needed for binary fields like the example below

The derive generates serde::Serialize and serde::Deserialize impls for CBOR protocols that need integer map keys, field-order arrays and semantic tags, such as COSE (RFC 9052). Map-shaped structs can also use #[serde(flatten)] for extension fields beside the registered integer-key subset. It implements cbor2::Cbor, exposing the declared keys, tag and array shape as runtime metadata. The original Rust field names stay intact for JSON and other serde formats.

use cbor2::Cbor;

#[derive(Debug, PartialEq, Cbor)]
#[cbor(tag = 18)]
struct CoseHeader {
    #[cbor(key = 1)]
    alg: i8,
    #[cbor(key = 4)]
    #[serde(with = "serde_bytes")]
    kid: Vec<u8>,
}

assert_eq!(CoseHeader::KEYS, &[("alg", 1), ("kid", 4)]);
assert_eq!(CoseHeader::TAG, Some(18));

Derive Macros§

Cbor
Derives serde::Serialize and serde::Deserialize with CBOR protocol details: integer map keys (#[cbor(key = <integer>)] on fields), field-order array structs (#[cbor(array)] on the container) and a CBOR tag (#[cbor(tag = <integer>)] on the container). The tag is written on encode and transparent on decode, so input is accepted with or without it. The declared details are also exposed through an implementation of the cbor2::Cbor trait, so the generated code requires the cbor2 crate under that name.