use crate::config::NetAddr;
fn _default_basepath() -> String {
crate::config::DEFAULT_BASEPATH.to_string()
}
fn _default_max_connections() -> u16 {
15
}
#[derive(
Clone, Default, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Deserialize, serde::Serialize,
)]
#[serde(default, deny_unknown_fields, rename_all = "snake_case")]
pub struct NetworkConfig {
pub(crate) address: NetAddr,
#[serde(default = "_default_basepath")]
pub(crate) basepath: String,
#[serde(default = "_default_max_connections")]
pub(crate) max_connections: u16,
pub(crate) open: bool,
}
impl NetworkConfig {
pub fn new() -> Self {
Self {
address: NetAddr::default(),
basepath: _default_basepath(),
max_connections: _default_max_connections(),
open: false,
}
}
pub const fn address(&self) -> &NetAddr {
&self.address
}
pub const fn address_mut(&mut self) -> &mut NetAddr {
&mut self.address
}
pub fn basepath(&self) -> &str {
&self.basepath
}
pub const fn max_connections(&self) -> u16 {
self.max_connections
}
pub const fn max_connections_mut(&mut self) -> &mut u16 {
&mut self.max_connections
}
pub fn should_open(self) -> Self {
Self { open: true, ..self }
}
pub fn should_not_open(self) -> Self {
Self {
open: false,
..self
}
}
pub fn with_address(self, address: NetAddr) -> Self {
Self { address, ..self }
}
pub fn with_basepath(self, basepath: impl ToString) -> Self {
Self {
basepath: basepath.to_string(),
..self
}
}
pub fn set_address(&mut self, address: NetAddr) {
self.address = address
}
pub fn set_basepath<T>(&mut self, basepath: T)
where
T: ToString,
{
self.basepath = basepath.to_string()
}
pub const fn set_max_connections(&mut self, max_connections: u16) {
self.max_connections = max_connections
}
pub fn as_socket_addr(&self) -> core::net::SocketAddr {
self.address.as_socket_addr()
}
pub async fn bind(&self) -> std::io::Result<tokio::net::TcpListener> {
self.address().bind().await
}
pub fn host(&self) -> &str {
self.address().host()
}
pub fn ip(&self) -> core::net::IpAddr {
self.address().ip()
}
pub fn open(&self) -> bool {
self.open
}
pub fn port(&self) -> u16 {
self.address.port
}
pub fn set_port(&mut self, port: u16) {
self.address.port = port;
}
pub fn with_port(self, port: u16) -> Self {
Self {
address: NetAddr {
port,
..self.address
},
..self
}
}
pub fn set_host(&mut self, host: impl ToString) {
self.address.host = host.to_string();
}
pub fn with_host(self, host: impl ToString) -> Self {
Self {
address: self.address.with_host(host),
..self
}
}
}
impl core::fmt::Debug for NetworkConfig {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(serde_json::to_string_pretty(self).unwrap().as_str())
}
}
impl core::fmt::Display for NetworkConfig {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(serde_json::to_string(self).unwrap().as_str())
}
}