kutil_http/
uri.rs

1use {
2    bytestring::*,
3    http::{uri::*, *},
4    std::{borrow::*, collections::*, result::Result, string::*},
5    url::form_urlencoded,
6    urlencoding::*,
7};
8
9//
10// PathAndQueryUtilities
11//
12
13/// [PathAndQuery] utilities.
14pub trait PathAndQueryUtilities {
15    /// Decoded path.
16    fn decoded_path(&self) -> Option<Cow<'_, str>>;
17
18    /// Decoded query.
19    fn decoded_query(&self) -> Option<Vec<(Cow<'_, str>, Cow<'_, str>)>>;
20
21    /// Decoded path.
22    fn decoded_query_map(&self) -> Option<BTreeMap<ByteString, ByteString>> {
23        self.decoded_query()
24            .map(|query| query.iter().map(|(name, value)| (name.as_ref().into(), value.as_ref().into())).collect())
25    }
26}
27
28impl PathAndQueryUtilities for PathAndQuery {
29    fn decoded_path(&self) -> Option<Cow<'_, str>> {
30        decode(self.path()).ok()
31    }
32
33    fn decoded_query(&self) -> Option<Vec<(Cow<'_, str>, Cow<'_, str>)>> {
34        self.query().map(|query| form_urlencoded::parse(query.as_bytes()).collect())
35    }
36}
37
38impl PathAndQueryUtilities for Uri {
39    fn decoded_path(&self) -> Option<Cow<'_, str>> {
40        self.path_and_query().and_then(|path_and_query| path_and_query.decoded_path())
41    }
42
43    fn decoded_query(&self) -> Option<Vec<(Cow<'_, str>, Cow<'_, str>)>> {
44        self.path_and_query().and_then(|path_and_query| path_and_query.decoded_query())
45    }
46}
47
48//
49// UriUtilities
50//
51
52/// [Uri] utilities.
53pub trait UriUtilities: PathAndQueryUtilities {
54    /// With new path.
55    fn with_path(&self, path: &str) -> Result<Uri, Error>;
56}
57
58impl UriUtilities for Uri {
59    fn with_path(&self, path: &str) -> Result<Uri, Error> {
60        //let mut path_and_query = encode(path).into_owned();
61        let mut path_and_query = String::from(path);
62        if let Some(query) = self.query() {
63            path_and_query = path_and_query + "?" + query;
64        }
65
66        let mut builder = Self::builder().path_and_query(path_and_query);
67
68        if let Some(scheme) = self.scheme() {
69            builder = builder.scheme(scheme.clone());
70        }
71
72        if let Some(authority) = self.authority() {
73            builder = builder.authority(authority.clone());
74        }
75
76        builder.build()
77    }
78}
79
80//
81// SetUri
82//
83
84/// Set [Uri].
85pub trait SetUri {
86    /// Set [Uri].
87    fn set_uri(&mut self, uri: Uri);
88
89    /// Set [Uri] path.
90    fn set_uri_path(&mut self, path: &str) -> Result<(), Error>;
91}
92
93impl<BodyT> SetUri for Request<BodyT> {
94    fn set_uri(&mut self, uri: Uri) {
95        *self.uri_mut() = uri;
96    }
97
98    fn set_uri_path(&mut self, path: &str) -> Result<(), Error> {
99        let uri = self.uri().with_path(path)?;
100        self.set_uri(uri);
101        Ok(())
102    }
103}