zaun_community_protocol/encoding.rs
1//! Canonical binary encoding of signed objects (specification §3.1, ADR-0006).
2//!
3//! | Type | Encoding |
4//! |---|---|
5//! | `u8`…`u64` | fixed width, big-endian |
6//! | `bool` | `0x00` / `0x01`; anything else is an error |
7//! | `bytes[N]` | exactly N bytes |
8//! | `bytes`, `string` | `u32` length, then the bytes (strings: valid UTF-8, not normalised) |
9//! | `option<T>` | `0x00`, or `0x01` then `T` |
10//! | `list<T>` | `u32` count, then each element |
11//!
12//! Every variable field has a limit, enforced by both the [`Writer`] and the [`Reader`], so a
13//! value that encodes also decodes. A length or count is checked against the limit and the
14//! remaining input before anything is allocated. There is exactly one encoding per value.
15
16mod error;
17mod impls;
18mod reader;
19mod writer;
20
21pub use error::{DecodeError, EncodeError};
22pub use reader::Reader;
23pub use writer::Writer;
24
25/// A type with a canonical encoding (fixed-size or self-limiting).
26pub trait Encode {
27 /// Appends the canonical encoding.
28 ///
29 /// # Errors
30 /// [`EncodeError`] when a field breaks its limit or rule.
31 fn encode(&self, w: &mut Writer) -> Result<(), EncodeError>;
32}
33
34/// A type with a canonical decoding.
35pub trait Decode: Sized {
36 /// Reads one value.
37 ///
38 /// # Errors
39 /// [`DecodeError`] for truncated, oversized or invalid input.
40 fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError>;
41}
42
43/// Encodes a top-level value.
44///
45/// # Errors
46/// [`EncodeError`] when a field breaks its limit or rule.
47pub fn to_bytes<T: Encode + ?Sized>(value: &T) -> Result<Vec<u8>, EncodeError> {
48 let mut w = Writer::new();
49 value.encode(&mut w)?;
50 Ok(w.into_bytes())
51}
52
53/// Decodes a top-level value, rejecting trailing bytes.
54///
55/// # Errors
56/// [`DecodeError`] for malformed input or trailing bytes.
57pub fn from_bytes<T: Decode>(bytes: &[u8]) -> Result<T, DecodeError> {
58 let mut r = Reader::new(bytes);
59 let value = T::decode(&mut r)?;
60 r.finish()?;
61 Ok(value)
62}
63
64#[cfg(test)]
65mod tests;