pzzld_server/config/types/
netaddr.rs

1/*
2    Appellation: server_addr <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5
6fn default_ip() -> String {
7    core::net::IpAddr::V4(core::net::Ipv4Addr::LOCALHOST).to_string()
8}
9
10fn default_port() -> u16 {
11    crate::DEFAULT_PORT
12}
13
14#[derive(
15    Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Deserialize, serde::Serialize,
16)]
17#[serde(default)]
18pub struct NetAddr {
19    #[serde(default = "default_ip")]
20    pub host: String,
21    #[serde(default = "default_port")]
22    pub port: u16,
23}
24
25impl NetAddr {
26    pub fn new(host: impl ToString, port: u16) -> Self {
27        Self {
28            host: host.to_string(),
29            port,
30        }
31    }
32
33    pub fn from_socket_addr(addr: core::net::SocketAddr) -> Self {
34        Self {
35            host: addr.ip().to_string(),
36            port: addr.port(),
37        }
38    }
39
40    pub fn localhost(port: u16) -> Self {
41        Self::new(default_ip(), port)
42    }
43
44    pub fn as_socket_addr(&self) -> core::net::SocketAddr {
45        self.to_string().parse().unwrap()
46    }
47    /// initialize a new listener, bound to the configured address
48    pub async fn bind(&self) -> std::io::Result<tokio::net::TcpListener> {
49        tokio::net::TcpListener::bind(&self.as_socket_addr()).await
50    }
51
52    pub fn ip(&self) -> core::net::IpAddr {
53        self.as_socket_addr().ip()
54    }
55
56    pub fn port(&self) -> u16 {
57        self.port
58    }
59
60    get!(host: String);
61    setwith!(host: String, port: u16);
62}
63
64impl Default for NetAddr {
65    fn default() -> Self {
66        Self {
67            host: crate::DEFAULT_HOST.to_string(),
68            port: crate::DEFAULT_PORT,
69        }
70    }
71}
72
73impl core::fmt::Display for NetAddr {
74    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
75        write!(f, "{host}:{port}", host = self.host, port = self.port)
76    }
77}
78
79impl core::str::FromStr for NetAddr {
80    type Err = Box<dyn core::error::Error>;
81
82    fn from_str(s: &str) -> Result<Self, Self::Err> {
83        let mut parts = s.split(':');
84        let host: core::net::IpAddr = parts.next().unwrap().parse()?;
85        let port = parts.next().unwrap().parse()?;
86        Ok(Self {
87            host: host.to_string(),
88            port,
89        })
90    }
91}
92
93impl From<core::net::SocketAddr> for NetAddr {
94    fn from(addr: core::net::SocketAddr) -> Self {
95        Self::from_socket_addr(addr)
96    }
97}