google_apis_common/
url.rs

1use std::borrow::Cow;
2
3use ::url::Url;
4use percent_encoding::{percent_encode, AsciiSet, CONTROLS};
5
6pub struct Params<'a> {
7    params: Vec<(&'a str, Cow<'a, str>)>,
8}
9
10impl<'a> Params<'a> {
11    pub fn with_capacity(capacity: usize) -> Self {
12        Self {
13            params: Vec::with_capacity(capacity),
14        }
15    }
16
17    pub fn push<I: Into<Cow<'a, str>>>(&mut self, param: &'a str, value: I) {
18        self.params.push((param, value.into()))
19    }
20
21    pub fn extend<I: Iterator<Item = (&'a String, IC)>, IC: Into<Cow<'a, str>>>(
22        &mut self,
23        params: I,
24    ) {
25        self.params
26            .extend(params.map(|(k, v)| (k.as_str(), v.into())))
27    }
28
29    pub fn get(&self, param_name: &str) -> Option<&str> {
30        self.params
31            .iter()
32            .find(|(name, _)| name == &param_name)
33            .map(|(_, param)| param.as_ref())
34    }
35
36    pub fn uri_replacement(
37        &self,
38        url: String,
39        param: &str,
40        from: &str,
41        url_encode: bool,
42    ) -> String {
43        const DEFAULT_ENCODE_SET: &AsciiSet = &CONTROLS
44            .add(b' ')
45            .add(b'"')
46            .add(b'#')
47            .add(b'<')
48            .add(b'>')
49            .add(b'`')
50            .add(b'?')
51            .add(b'{')
52            .add(b'}');
53        if url_encode {
54            let mut replace_with: Cow<str> = self.get(param).unwrap_or_default().into();
55            if from.as_bytes()[1] == b'+' {
56                replace_with = percent_encode(replace_with.as_bytes(), DEFAULT_ENCODE_SET)
57                    .to_string()
58                    .into();
59            }
60            url.replace(from, &replace_with)
61        } else {
62            let replace_with = self
63                .get(param)
64                .expect("to find substitution value in params");
65
66            url.replace(from, replace_with)
67        }
68    }
69
70    pub fn remove_params(&mut self, to_remove: &[&str]) {
71        self.params.retain(|(n, _)| !to_remove.contains(n))
72    }
73
74    pub fn inner_mut(&mut self) -> &mut Vec<(&'a str, Cow<'a, str>)> {
75        self.params.as_mut()
76    }
77
78    pub fn parse_with_url(&self, url: &str) -> Url {
79        Url::parse_with_params(url, &self.params).unwrap()
80    }
81}