From 104cdac0584852d65c24527a01986c894fc0f214 Mon Sep 17 00:00:00 2001 From: Claude DevOps Engineer Date: Thu, 29 Jan 2026 04:02:52 -0300 Subject: [PATCH] Add try_new() non-panicking constructor Add try_new() that returns io::Result instead of panicking when UdpSocket::bind() or set_timeout() fails. Document the panic condition on new() and delegate to try_new().expect(). Closes #11 --- src/lib.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 69e79fe..adf656e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -61,13 +61,24 @@ impl Default for SntpRequest { impl SntpRequest { /// Creates a new SNTP request object. + /// + /// # Panics + /// + /// Panics if the UDP socket cannot be bound or the timeout cannot be set. + /// Use [`try_new`](Self::try_new) for a non-panicking alternative. pub fn new() -> SntpRequest { + Self::try_new().expect("failed to create SNTP request") + } + + /// Creates a new SNTP request object, returning an error instead of + /// panicking if the UDP socket cannot be bound or the timeout cannot be set. + pub fn try_new() -> io::Result { let sntp = SntpRequest { - socket: UdpSocket::bind("0.0.0.0:0").unwrap(), + socket: UdpSocket::bind("0.0.0.0:0")?, kiss_of_death: Cell::new(false), }; - sntp.set_timeout(Duration::from_secs(5)).unwrap(); - sntp + sntp.set_timeout(Duration::from_secs(5))?; + Ok(sntp) } #[inline]