pzzld_server/config/kinds/
network.rs

1/*
2    Appellation: server <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5use crate::config::NetAddr;
6
7#[derive(
8    Clone,
9    Debug,
10    Default,
11    Eq,
12    Hash,
13    Ord,
14    PartialEq,
15    PartialOrd,
16    serde::Deserialize,
17    serde::Serialize,
18)]
19#[serde(default)]
20pub struct NetworkConfig {
21    pub(crate) address: NetAddr,
22    pub(crate) basepath: Option<String>,
23    pub(crate) max_connections: Option<u16>,
24    pub(crate) open: bool,
25}
26
27impl NetworkConfig {
28    pub fn new() -> Self {
29        Self {
30            address: NetAddr::default(),
31            basepath: None,
32            max_connections: None,
33            open: false,
34        }
35    }
36
37    getter! {
38        address: NetAddr,
39        open: bool,
40    }
41
42    setwith! {
43        address: NetAddr,
44        open: bool,
45    }
46    /// Returns an instance of the address as a [SocketAddr](core::net::SocketAddr)
47    pub fn as_socket_addr(&self) -> core::net::SocketAddr {
48        self.address.as_socket_addr()
49    }
50
51    pub async fn bind(&self) -> std::io::Result<tokio::net::TcpListener> {
52        self.address().bind().await
53    }
54    /// Returns the host of the address
55    pub fn host(&self) -> &str {
56        self.address().host()
57    }
58    /// Returns the ip of the address
59    pub fn ip(&self) -> core::net::IpAddr {
60        self.address().ip()
61    }
62    /// Returns the port of the address
63    pub fn port(&self) -> u16 {
64        self.address.port
65    }
66
67    pub fn set_port(&mut self, port: u16) {
68        self.address.port = port;
69    }
70
71    pub fn with_port(self, port: u16) -> Self {
72        Self {
73            address: NetAddr {
74                port,
75                ..self.address
76            },
77            ..self
78        }
79    }
80
81    pub fn set_host(&mut self, host: impl ToString) {
82        self.address.host = host.to_string();
83    }
84
85    pub fn with_host(self, host: impl ToString) -> Self {
86        Self {
87            address: self.address.with_host(host),
88            ..self
89        }
90    }
91
92    pub fn set_basepath(&mut self, basepath: impl ToString) {
93        self.basepath = Some(basepath.to_string());
94    }
95
96    pub fn with_basepath(self, basepath: impl ToString) -> Self {
97        Self {
98            basepath: Some(basepath.to_string()),
99            ..self
100        }
101    }
102}