hyperlocal_next/
uri.rs

1use hyper::Uri as HyperUri;
2use std::path::Path;
3
4/// A convenience type that can be used to construct Unix Domain Socket URIs
5///
6/// This type implements `Into<hyper::Uri>`.
7///
8/// # Example
9/// ```
10/// use hyperlocal::Uri;
11/// use hyper::Uri as HyperUri;
12///
13/// let uri: HyperUri = Uri::new("/tmp/hyperlocal.sock", "/").into();
14/// ```
15#[derive(Debug, Clone)]
16pub struct Uri {
17    hyper_uri: HyperUri,
18}
19
20impl Uri {
21    /// Create a new `[Uri]` from a socket address and a path
22    ///
23    /// # Panics
24    /// Will panic if path is not absolute and/or a malformed path string.
25    pub fn new(socket: impl AsRef<Path>, path: &str) -> Self {
26        let host = hex::encode(socket.as_ref().to_string_lossy().as_bytes());
27        let host_str = format!("unix://{host}:0{path}");
28        let hyper_uri: HyperUri = host_str.parse().unwrap();
29
30        Self { hyper_uri }
31    }
32}
33
34impl From<Uri> for HyperUri {
35    fn from(uri: Uri) -> Self {
36        uri.hyper_uri
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use super::Uri;
43    use hyper::Uri as HyperUri;
44
45    #[test]
46    fn test_unix_uri_into_hyper_uri() {
47        let unix: HyperUri = Uri::new("foo.sock", "/").into();
48        let expected: HyperUri = "unix://666f6f2e736f636b:0/".parse().unwrap();
49        assert_eq!(unix, expected);
50    }
51}