keynesis_network/
session_id.rs

1use std::{fmt, str::FromStr};
2
3/// unique identifier of a session established between 2 peers
4///
5/// this session identifier is generated with the handshake and
6/// is unique to the connection (reconnecting to the same peer
7/// will generate a new [`SessionId`])
8#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
9pub struct SessionId([u8; 64]);
10
11impl SessionId {
12    pub const SIZE: usize = 64;
13
14    pub(crate) const fn new(session: [u8; Self::SIZE]) -> Self {
15        Self(session)
16    }
17}
18
19impl AsRef<[u8]> for SessionId {
20    fn as_ref(&self) -> &[u8] {
21        self.0.as_ref()
22    }
23}
24
25impl fmt::Display for SessionId {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.write_str(&hex::encode(&self.0))
28    }
29}
30
31impl fmt::Debug for SessionId {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        f.debug_tuple("SessionId")
34            .field(&hex::encode(&self.0))
35            .finish()
36    }
37}
38
39impl FromStr for SessionId {
40    type Err = hex::FromHexError;
41    fn from_str(s: &str) -> Result<Self, Self::Err> {
42        let mut session_id = SessionId([0; 64]);
43        hex::decode_to_slice(s, &mut session_id.0)?;
44        Ok(session_id)
45    }
46}