hyperlocal_v07/
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)]
16pub struct Uri {
17    hyper_uri: HyperUri,
18}
19
20impl Uri {
21    /// Create a new `[Uri]` from a socket address and a path
22    pub fn new(socket: impl AsRef<Path>, path: &str) -> Self {
23        let host = hex::encode(socket.as_ref().to_string_lossy().as_bytes());
24        let host_str = format!("unix://{}:0{}", host, path);
25        let hyper_uri: HyperUri = host_str.parse().unwrap();
26
27        Self { hyper_uri }
28    }
29}
30
31impl From<Uri> for HyperUri {
32    fn from(uri: Uri) -> Self {
33        uri.hyper_uri
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::Uri;
40    use hyper::Uri as HyperUri;
41
42    #[test]
43    fn test_unix_uri_into_hyper_uri() {
44        let unix: HyperUri = Uri::new("foo.sock", "/").into();
45        let expected: HyperUri = "unix://666f6f2e736f636b:0/".parse().unwrap();
46        assert_eq!(unix, expected);
47    }
48}