From 03a3a61d0853d73358b1e261f88d3a3a89e9c336 Mon Sep 17 00:00:00 2001 From: Hugo Osvaldo Barrera Date: Fri, 23 Aug 2024 15:10:25 +0200 Subject: [PATCH] Return an error if path is invalid Instead of panicking when a path is invalid, return an error which can properly be handled by the caller. Note that this is a backwards-incompatible change, so the next version should be 0.10.0. Updating call-sites is usually trivial. --- examples/client.rs | 2 +- src/uri.rs | 17 +++++++++-------- tests/server_client.rs | 2 +- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/examples/client.rs b/examples/client.rs index 701cd1f..7e8354e 100644 --- a/examples/client.rs +++ b/examples/client.rs @@ -7,7 +7,7 @@ use tokio::io::{self, AsyncWriteExt as _}; #[tokio::main] async fn main() -> Result<(), Box> { - let url = Uri::new("/tmp/hyperlocal.sock", "/").into(); + let url = Uri::new("/tmp/hyperlocal.sock", "/").unwrap().into(); let client: Client> = Client::unix(); diff --git a/src/uri.rs b/src/uri.rs index 9c5d23e..6bf57c6 100644 --- a/src/uri.rs +++ b/src/uri.rs @@ -1,4 +1,4 @@ -use hyper::Uri as HyperUri; +use hyper::{http::uri::InvalidUri, Uri as HyperUri}; use std::path::Path; /// A convenience type that can be used to construct Unix Domain Socket URIs @@ -10,7 +10,7 @@ use std::path::Path; /// use hyper::Uri as HyperUri; /// use hyperlocal::Uri; /// -/// let uri: HyperUri = Uri::new("/tmp/hyperlocal.sock", "/").into(); +/// let uri: HyperUri = Uri::new("/tmp/hyperlocal.sock", "/").unwrap().into(); /// ``` #[derive(Debug, Clone)] pub struct Uri { @@ -20,17 +20,18 @@ pub struct Uri { impl Uri { /// Create a new `[Uri]` from a socket address and a path /// - /// # Panics - /// Will panic if path is not absolute and/or a malformed path string. + /// # Errors + /// + /// Returns an error if path is not absolute and/or a malformed path string. pub fn new( socket: impl AsRef, path: &str, - ) -> Self { + ) -> Result { let host = hex::encode(socket.as_ref().to_string_lossy().as_bytes()); let host_str = format!("unix://{host}:0{path}"); - let hyper_uri: HyperUri = host_str.parse().unwrap(); + let hyper_uri: HyperUri = host_str.parse()?; - Self { hyper_uri } + Ok(Self { hyper_uri }) } } @@ -47,7 +48,7 @@ mod tests { #[test] fn test_unix_uri_into_hyper_uri() { - let unix: HyperUri = Uri::new("foo.sock", "/").into(); + let unix: HyperUri = Uri::new("foo.sock", "/").unwrap().into(); let expected: HyperUri = "unix://666f6f2e736f636b:0/".parse().unwrap(); assert_eq!(unix, expected); } diff --git a/tests/server_client.rs b/tests/server_client.rs index 02941e0..957bc34 100644 --- a/tests/server_client.rs +++ b/tests/server_client.rs @@ -43,7 +43,7 @@ async fn test_server_client() -> Result<(), Box> { let client: Client> = Client::unix(); - let url = Uri::new(path, "/").into(); + let url = Uri::new(path, "/").unwrap().into(); let mut response = client.get(url).await?; let mut bytes = Vec::default();