From 854cfbc21962deb6c56f895ce2626079fad78ff1 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Tue, 4 Jun 2024 15:59:37 +0100 Subject: [PATCH] Replace bind_{tcp,unix} with a single function Same reasons as the connect_{tcp,unix} commit. Although there is currently only one call site. --- src/server.rs | 8 ++------ src/socketwrapper.rs | 25 ++++++++++++------------- 2 files changed, 14 insertions(+), 19 deletions(-) diff --git a/src/server.rs b/src/server.rs index 956662c..67a6b77 100644 --- a/src/server.rs +++ b/src/server.rs @@ -5,7 +5,7 @@ use tokio::task; use tracing::{error, info, info_span, warn, Instrument}; use crate::client; -use crate::config::{Address, Config}; +use crate::config::Config; use crate::instance::InstanceMap; use crate::socketwrapper::Listener; @@ -13,11 +13,7 @@ pub async fn run(config: &Config) -> Result<()> { let instance_map = InstanceMap::new(config).await; let next_client_id = AtomicUsize::new(0); - let listener = match config.listen { - Address::Tcp(ip_addr, port) => Listener::bind_tcp((ip_addr, port).into()).await, - #[cfg(target_family = "unix")] - Address::Unix(ref path) => Listener::bind_unix(path), - } + let listener = Listener::bind(&config.listen).await .context("listen")?; loop { match listener.accept().await { diff --git a/src/socketwrapper.rs b/src/socketwrapper.rs index 0252bfa..cde593c 100644 --- a/src/socketwrapper.rs +++ b/src/socketwrapper.rs @@ -1,7 +1,5 @@ #[cfg(target_family = "unix")] use std::fs; -#[cfg(target_family = "unix")] -use std::path::Path; use std::pin::Pin; use std::task::{Context, Poll}; use std::{io, net}; @@ -235,18 +233,19 @@ pub enum Listener { } impl Listener { - pub async fn bind_tcp(addr: net::SocketAddr) -> io::Result { - Ok(Listener::Tcp(TcpListener::bind(addr).await?)) - } - - #[cfg(target_family = "unix")] - pub fn bind_unix>(addr: T) -> io::Result { - match fs::remove_file(&addr) { - Ok(()) => (), - Err(e) if e.kind() == io::ErrorKind::NotFound => (), - Err(e) => return Err(e), + pub async fn bind(addr: &Address) -> io::Result { + match addr { + Address::Tcp(ip_addr, port) => Ok(Listener::Tcp(TcpListener::bind((*ip_addr, *port)).await?)), + #[cfg(target_family = "unix")] + Address::Unix(path) => { + match fs::remove_file(&path) { + Ok(()) => (), + Err(e) if e.kind() == io::ErrorKind::NotFound => (), + Err(e) => return Err(e), + } + Ok(Listener::Unix(UnixListener::bind(path)?)) + } } - Ok(Listener::Unix(UnixListener::bind(addr)?)) } pub async fn accept(&self) -> io::Result<(Stream, SocketAddr)> {