Expand description
Macros for deriving primitive Decode
and Encode
implementations on types containing decodable/encodable fields.
These derivations are intended to be stable, however, if you’re using these macros to implement a specific protocol you really should write tests to ensure the binary encoding matches your expectations.
Example
Derive macros provide a simple way to implement Encode
and Decode
for objects with (enc|dec)odable fields by (de)serializing each field in order.
For detail on derived implementations see the Encode and Decode macros.
#[derive(Debug, PartialEq, Encode, Decode)]
struct Something {
a: u8,
b: u16,
c: u8,
}
let a1 = Something{ a: 0x10, b: 0xabcd, c: 0x11 };
let n1 = a1.encode(&mut buff[..]).unwrap();
// Encoded data is little endian, ordered by struct field
assert_eq!(&buff[..n1], &[0x10, 0xcd, 0xab, 0x11]);
let (a2, n2) = Something::decode(&buff[..n1]).unwrap();
assert_eq!(a1, a2);
Customisation
Error Types
Derived error types may be overridden with a struct level attribute
#[encdec(error = "E")]
where E
is a user error type implementing
From<encdec::Error>
Encode/Decode methods
Field encode/decode methods may be overridden using a field level attribute
#[encdec(with = "M")]
on a field of type T
, where M
is a module providing:
fn enc(&T, &mut [u8]) -> Result<usize, E>
fn enc_len(&T) -> Result<usize, E>
fn dec(&[u8]) -> Result<(T, usize), E>
Individual methods may be overridden if required using #[encdec(enc = "..", enc_len = "..", dec = "..")]
with the same type signatures / constraints as above.
Derive Macros
#[derive(Decode)]
support.#[derive(DecodeOwned)]
support.#[derive(Encode)]
support.