From f76cf7786e77fac070b733d9b8d9c5e1a5fb1def Mon Sep 17 00:00:00 2001 From: Stephen Seo Date: Wed, 19 Mar 2025 16:58:56 +0900 Subject: [PATCH] Refactor reconnect code The reconnection "impl" function will only be used by one other function. To prevent future misuse, the "impl" function was moved into a closure inside the function that uses it. --- src/mpd_handler.rs | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/src/mpd_handler.rs b/src/mpd_handler.rs index 0704bcf..7599e54 100644 --- a/src/mpd_handler.rs +++ b/src/mpd_handler.rs @@ -241,32 +241,31 @@ fn read_line( Err((String::from("Newline not reached"), result)) } -fn restart_stream_impl( - state_handle: &mut RwLockWriteGuard<'_, MPDHandlerState>, -) -> Result<(), String> { - let peer = state_handle - .stream - .peer_addr() - .map_err(|_| String::from("Failed to get TCP stream peer addr/port"))?; - state_handle - .stream - .shutdown(std::net::Shutdown::Both) - .map_err(|_| String::from("Failed to cleanup TCP stream"))?; - state_handle.stream = TcpStream::connect_timeout(&peer, CONNECT_TIMEOUT) - .map_err(|_| String::from("Failed to reconnect"))?; - state_handle - .stream - .set_nonblocking(true) - .map_err(|_| String::from("Failed to set non-blocking on restarted TCP stream"))?; - Ok(()) -} - fn restart_stream( state_handle: &mut RwLockWriteGuard<'_, MPDHandlerState>, log_level: LogLevel, ) -> Result<(), String> { thread::sleep(PRE_RESTART_WAIT); - let result = restart_stream_impl(state_handle); + + let fn_impl = |state_handle: &mut RwLockWriteGuard<'_, MPDHandlerState>| -> Result<(), String> { + let peer = state_handle + .stream + .peer_addr() + .map_err(|_| String::from("Failed to get TCP stream peer addr/port"))?; + state_handle + .stream + .shutdown(std::net::Shutdown::Both) + .map_err(|_| String::from("Failed to cleanup TCP stream"))?; + state_handle.stream = TcpStream::connect_timeout(&peer, CONNECT_TIMEOUT) + .map_err(|_| String::from("Failed to reconnect"))?; + state_handle + .stream + .set_nonblocking(true) + .map_err(|_| String::from("Failed to set non-blocking on restarted TCP stream"))?; + Ok(()) + }; + + let result = fn_impl(state_handle); if let Err(e) = result { log("Failed to reconnect.", LogState::Error, LogLevel::Error); state_handle.stop_flag.store(true, Ordering::Release); -- 2.49.0