ate_crypto/spec/
node_id.rs

1use core::fmt;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6pub enum NodeId {
7    Unknown,
8    Client(u64),
9    Server(u32, u32),
10}
11
12impl Default for NodeId {
13    fn default() -> Self {
14        NodeId::Unknown
15    }
16}
17
18impl fmt::Display
19for NodeId
20{
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        match self {
23            NodeId::Unknown => write!(f, "unknown"),
24            NodeId::Client(id) => write!(f, "client({})", id),
25            NodeId::Server(server_id, node_id) => write!(f, "server(id={}, node={})", server_id, node_id),
26        }
27    }
28}
29
30impl NodeId {
31    pub fn generate_client_id() -> NodeId {
32        let client_id = fastrand::u64(..);
33        NodeId::Client(client_id)
34    }
35
36    pub fn generate_server_id(node_id: u32) -> NodeId {
37        let server_id = fastrand::u32(..);
38        NodeId::Server(server_id, node_id)
39    }
40
41    pub fn to_string(&self) -> String {
42        match self {
43            NodeId::Unknown => "[new]".to_string(),
44            NodeId::Client(a) => hex::encode(a.to_be_bytes()).to_uppercase(),
45            NodeId::Server(_, b) => format!("n{}", b),
46        }
47    }
48
49    pub fn to_short_string(&self) -> String {
50        match self {
51            NodeId::Unknown => "[new]".to_string(),
52            NodeId::Client(a) => {
53                let client_id = hex::encode(a.to_be_bytes()).to_uppercase();
54                format!("{}", &client_id[..4])
55            }
56            NodeId::Server(_, a) => format!("n{}", a),
57        }
58    }
59}