Skip to main content

zaun_community_protocol/encoding/
impls.rs

1//! Canonical encodings of primitives, keys and identifiers.
2
3use super::{Decode, DecodeError, Encode, EncodeError, Reader, Writer};
4use crate::ids::{Challenge, CommunityId, HostId, Nonce};
5use crate::keys::{PUBLIC_KEY_LEN, PublicKey, Suite};
6
7macro_rules! primitive {
8    ($($ty:ident),*) => {$(
9        impl Encode for $ty {
10            fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
11                w.$ty(*self);
12                Ok(())
13            }
14        }
15
16        impl Decode for $ty {
17            fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
18                r.$ty()
19            }
20        }
21    )*};
22}
23
24primitive!(u8, u16, u32, u64, bool);
25
26impl<const N: usize> Encode for [u8; N] {
27    fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
28        w.fixed(self);
29        Ok(())
30    }
31}
32
33impl<const N: usize> Decode for [u8; N] {
34    fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
35        r.array()
36    }
37}
38
39/// `PublicKey` as a field (§3.4): `suite u8 ‖ components`, no length prefix. An unknown suite
40/// byte is rejected before the components are read.
41impl Encode for PublicKey {
42    fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
43        w.fixed(self.as_bytes());
44        Ok(())
45    }
46}
47
48impl Decode for PublicKey {
49    fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
50        let suite = r.peek_u8()?;
51        Suite::from_byte(suite).ok_or(DecodeError::UnknownSuite(suite))?;
52        let bytes = r.fixed(PUBLIC_KEY_LEN)?;
53        PublicKey::from_bytes(bytes).map_err(|_| DecodeError::UnknownSuite(suite))
54    }
55}
56
57macro_rules! byte_id {
58    ($($ty:ident),*) => {$(
59        impl Encode for $ty {
60            fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
61                w.fixed(self.as_bytes());
62                Ok(())
63            }
64        }
65
66        impl Decode for $ty {
67            fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
68                r.array().map($ty::from_bytes)
69            }
70        }
71    )*};
72}
73
74byte_id!(CommunityId, HostId, Nonce, Challenge);