Skip to main content

cliquenet/
msg.rs

1mod frame;
2mod trailer;
3
4pub mod hello;
5
6use std::fmt;
7
8pub use frame::{FrameType, Header, InvalidHeader};
9pub use trailer::Trailer;
10
11/// Max. message size using noise protocol.
12pub const MAX_NOISE_MESSAGE_SIZE: usize = 64 * 1024;
13
14/// Max. number of bytes for payload data.
15pub const MAX_PAYLOAD_SIZE: usize = MAX_NOISE_MESSAGE_SIZE - RESERVED_TAG_SIZE;
16
17/// Space reserved for the AEAD tag (16 are required, we add some extra margin).
18pub(crate) const RESERVED_TAG_SIZE: usize = 32;
19
20/// Slots contain messages.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
22pub struct Slot(pub(crate) u64);
23
24impl Slot {
25    pub const MIN: Slot = Slot(u64::MIN);
26    pub const MAX: Slot = Slot(u64::MAX);
27
28    pub const fn new(n: u64) -> Self {
29        Self(n)
30    }
31}
32
33impl From<Slot> for u64 {
34    fn from(s: Slot) -> Self {
35        s.0
36    }
37}
38
39impl fmt::Display for Slot {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        self.0.fmt(f)
42    }
43}
44
45/// A message identifier.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
47pub struct MsgId(pub(crate) u64);
48
49impl MsgId {
50    pub const fn new(n: u64) -> Self {
51        Self(n)
52    }
53}
54
55impl From<MsgId> for u64 {
56    fn from(i: MsgId) -> Self {
57        i.0
58    }
59}
60
61#[derive(Debug, Clone, Copy)]
62pub struct Ack(pub [u8; 16]);
63
64impl From<(Slot, MsgId)> for Ack {
65    fn from((s, i): (Slot, MsgId)) -> Self {
66        let s = u64::to_be_bytes(s.0);
67        let i = u64::to_be_bytes(i.0);
68        let mut a = [0; 16];
69        a[..8].copy_from_slice(&s);
70        a[8..].copy_from_slice(&i);
71        Self(a)
72    }
73}
74
75impl From<Ack> for (Slot, MsgId) {
76    fn from(a: Ack) -> Self {
77        let s = Slot(u64::from_be_bytes(a.0[..8].try_into().expect("8 bytes")));
78        let i = MsgId(u64::from_be_bytes(a.0[8..].try_into().expect("8 bytes")));
79        (s, i)
80    }
81}
82
83impl TryFrom<&[u8]> for Ack {
84    type Error = ();
85
86    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
87        Ok(Ack(value.try_into().map_err(|_| ())?))
88    }
89}