zero_trust_rps/common/
ip_display.rs1#[cfg(not(debug_assertions))]
2use std::sync::LazyLock;
3use std::{fmt::Display, net::SocketAddr};
4
5#[cfg(not(debug_assertions))]
6static SECRET: LazyLock<[u8; 32]> = LazyLock::new(|| super::utils::get_random_bytes());
7
8#[derive(PartialEq, Eq, Hash, Clone, Copy)]
9pub struct IpDisplay {
10 addr: SocketAddr,
11}
12
13impl From<SocketAddr> for IpDisplay {
14 fn from(value: SocketAddr) -> Self {
15 IpDisplay { addr: value }
16 }
17}
18
19impl Display for IpDisplay {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 if cfg!(debug_assertions) {
22 self.addr.fmt(f)
23 } else {
24 #[cfg(debug_assertions)]
25 unreachable!();
26 #[cfg(not(debug_assertions))]
27 {
28 use std::net::IpAddr;
29
30 let mut hasher = blake3::Hasher::new_keyed(&*SECRET);
31
32 hasher.update(&[self.addr.is_ipv4() as u8]);
33 match self.addr.ip().to_canonical() {
34 IpAddr::V4(addr) => hasher.update(&addr.octets()),
35 IpAddr::V6(addr) => hasher.update(&addr.octets()),
36 };
37
38 let hex = hasher.finalize().to_hex();
39 write!(f, "{}:{}", &hex[..10], self.addr.port())
40 }
41 }
42 }
43}
44
45impl std::fmt::Debug for IpDisplay {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 write!(f, "{}", self)
48 }
49}