use std::{
fmt::{Display, Formatter, Result},
net::SocketAddr,
};
const DEFAULT_SERVER_DESCRIPTION: &str = concat!("trillium v", env!("CARGO_PKG_VERSION"));
#[derive(Debug, Clone)]
pub struct Info {
server_description: String,
listener_description: String,
tcp_socket_addr: Option<SocketAddr>,
}
impl Default for Info {
fn default() -> Self {
Self {
server_description: DEFAULT_SERVER_DESCRIPTION.into(),
listener_description: String::new(),
tcp_socket_addr: None,
}
}
}
impl Display for Info {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.write_fmt(format_args!(
"{} listening on {}",
self.server_description(),
self.listener_description(),
))
}
}
impl Info {
pub fn server_description(&self) -> &str {
&self.server_description
}
pub fn listener_description(&self) -> &str {
&self.listener_description
}
pub const fn tcp_socket_addr(&self) -> Option<&SocketAddr> {
self.tcp_socket_addr.as_ref()
}
pub fn server_description_mut(&mut self) -> &mut String {
&mut self.server_description
}
pub fn listener_description_mut(&mut self) -> &mut String {
&mut self.listener_description
}
}
impl From<&str> for Info {
fn from(description: &str) -> Self {
Self {
server_description: String::from(DEFAULT_SERVER_DESCRIPTION),
listener_description: String::from(description),
..Self::default()
}
}
}
impl From<SocketAddr> for Info {
fn from(socket_addr: SocketAddr) -> Self {
Self {
server_description: String::from(DEFAULT_SERVER_DESCRIPTION),
listener_description: socket_addr.to_string(),
tcp_socket_addr: Some(socket_addr),
}
}
}
#[cfg(unix)]
impl From<std::os::unix::net::SocketAddr> for Info {
fn from(s: std::os::unix::net::SocketAddr) -> Self {
Self {
server_description: String::from(DEFAULT_SERVER_DESCRIPTION),
listener_description: format!("{s:?}"),
tcp_socket_addr: None,
}
}
}