hyperlocal_with_windows/
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 hyper::Uri as HyperUri;
11/// use hyperlocal_with_windows::Uri;
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(
26        socket: impl AsRef<Path>,
27        path: &str,
28    ) -> Self {
29        let host = hex::encode(socket.as_ref().to_string_lossy().as_bytes());
30        let host_str = format!("unix://{host}:0{path}");
31        let hyper_uri: HyperUri = host_str.parse().unwrap();
32
33        Self { hyper_uri }
34    }
35}
36
37impl From<Uri> for HyperUri {
38    fn from(uri: Uri) -> Self {
39        uri.hyper_uri
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::Uri;
46    use hyper::Uri as HyperUri;
47
48    #[test]
49    fn test_unix_uri_into_hyper_uri() {
50        let unix: HyperUri = Uri::new("foo.sock", "/").into();
51        let expected: HyperUri = "unix://666f6f2e736f636b:0/".parse().unwrap();
52        assert_eq!(unix, expected);
53    }
54}