1use {
2 bytestring::*,
3 http::{uri::*, *},
4 std::{borrow::*, collections::*, result::Result, string::*},
5 url::form_urlencoded,
6 urlencoding::*,
7};
8
9pub trait PathAndQueryUtilities {
15 fn decoded_path(&self) -> Option<Cow<'_, str>>;
17
18 fn decoded_query(&self) -> Option<Vec<(Cow<'_, str>, Cow<'_, str>)>>;
20
21 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
48pub trait UriUtilities: PathAndQueryUtilities {
54 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 = 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
80pub trait SetUri {
86 fn set_uri(&mut self, uri: Uri);
88
89 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}