Skip to main content

psicose/p2p/
peer.rs

1//! Node identity. Belongs to the session/P2P layer, never to the frame.
2
3/// 64-bit peer identity.
4///
5/// ```text
6/// Peer A
7///   │
8///   │ PeerId = "alice"
9///   ▼
10/// PSICOSE session
11/// ```
12///
13/// The 4-byte wire frame does not carry it: the hello exchange transmits
14/// it as ordinary payload bytes, one DATA frame per byte.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
16pub struct PeerId {
17    bytes: [u8; PeerId::LEN],
18}
19
20impl PeerId {
21    /// Identity size on the wire, in payload bytes.
22    pub const LEN: usize = 8;
23
24    /// Builds an identity from raw bytes. How they are generated (random,
25    /// hash of a key, serial number) is the application's business.
26    pub const fn new(bytes: [u8; PeerId::LEN]) -> Self {
27        PeerId { bytes }
28    }
29
30    /// Pads `label` with zeros to 8 bytes. Truncates if longer.
31    ///
32    /// ```
33    /// use psicose::PeerId;
34    /// assert_eq!(PeerId::from_label(b"alice").as_bytes()[0], b'a');
35    /// ```
36    pub const fn from_label(label: &[u8]) -> Self {
37        let mut bytes = [0u8; PeerId::LEN];
38        let mut i = 0;
39        while i < label.len() && i < PeerId::LEN {
40            bytes[i] = label[i];
41            i += 1;
42        }
43        PeerId { bytes }
44    }
45
46    /// The raw 8 bytes.
47    pub const fn as_bytes(&self) -> [u8; PeerId::LEN] {
48        self.bytes
49    }
50}
51
52impl From<[u8; PeerId::LEN]> for PeerId {
53    fn from(bytes: [u8; PeerId::LEN]) -> Self {
54        PeerId::new(bytes)
55    }
56}
57
58impl From<PeerId> for [u8; PeerId::LEN] {
59    fn from(id: PeerId) -> Self {
60        id.bytes
61    }
62}
63
64impl core::fmt::Display for PeerId {
65    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
66        if let Some(label) = label_bytes(&self.bytes) {
67            return f.write_str(label);
68        }
69        let b = &self.bytes;
70        write!(
71            f,
72            "{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}",
73            b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]
74        )
75    }
76}
77
78fn label_bytes(bytes: &[u8; 8]) -> Option<&str> {
79    let mut n = 0usize;
80    while n < 8 && bytes[n] != 0 {
81        let c = bytes[n];
82        if !c.is_ascii_graphic() && c != b' ' {
83            return None;
84        }
85        n += 1;
86    }
87    if n == 0 {
88        return None;
89    }
90    let mut i = n;
91    while i < 8 {
92        if bytes[i] != 0 {
93            return None;
94        }
95        i += 1;
96    }
97    core::str::from_utf8(&bytes[..n]).ok()
98}
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    #[test]
105    fn roundtrips_raw_bytes() {
106        let id = PeerId::new([0x82, 0xA1, 0, 1, 2, 3, 4, 5]);
107        assert_eq!(id.as_bytes(), [0x82, 0xA1, 0, 1, 2, 3, 4, 5]);
108        assert_eq!(PeerId::new(id.as_bytes()), id);
109        assert_eq!(PeerId::from(id.as_bytes()), id);
110        assert_eq!(<[u8; 8]>::from(id), id.as_bytes());
111    }
112
113    #[test]
114    fn distinct_bytes_are_distinct_peers() {
115        assert_ne!(PeerId::new([0; 8]), PeerId::new([1, 0, 0, 0, 0, 0, 0, 0]));
116    }
117
118    #[test]
119    fn from_label_pads_and_truncates() {
120        let alice = PeerId::from_label(b"alice");
121        assert_eq!(&alice.as_bytes()[..5], b"alice");
122        assert_eq!(alice.as_bytes()[5], 0);
123        assert_eq!(PeerId::from_label(b"toolongname").as_bytes(), *b"toolongn");
124    }
125
126    #[test]
127    fn display_prints_label_or_hex() {
128        let mut buf = [0u8; 16];
129        let alice = PeerId::from_label(b"alice");
130        let n = write_id(&alice, &mut buf);
131        assert_eq!(&buf[..n], b"alice");
132
133        let raw = PeerId::new([0x82, 0xA1, 0, 1, 2, 3, 4, 5]);
134        let n = write_id(&raw, &mut buf);
135        assert_eq!(&buf[..n], b"82A1000102030405");
136    }
137
138    fn write_id(id: &PeerId, buf: &mut [u8]) -> usize {
139        use core::fmt::Write;
140        struct Sink<'a> {
141            buf: &'a mut [u8],
142            n: usize,
143        }
144        impl Write for Sink<'_> {
145            fn write_str(&mut self, s: &str) -> core::fmt::Result {
146                let bytes = s.as_bytes();
147                if self.n + bytes.len() > self.buf.len() {
148                    return Err(core::fmt::Error);
149                }
150                self.buf[self.n..self.n + bytes.len()].copy_from_slice(bytes);
151                self.n += bytes.len();
152                Ok(())
153            }
154        }
155        let mut sink = Sink { buf, n: 0 };
156        let _ = write!(sink, "{id}");
157        sink.n
158    }
159}