1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
extern crate percent_encoding;

use percent_encoding::{percent_decode, utf8_percent_encode, QUERY_ENCODE_SET};
use std::iter::Iterator;

/// A query string. Holds a list of `(key,value)`.
///
/// Examples
///
/// Parameters can be get by their names.
///
/// ```
/// let qs = qstring::QString::from("?foo=bar%20baz");
/// let foo = qs.get("foo").unwrap();
/// assert_eq!(foo, "bar baz");
/// ```
///
/// Parameters not found are `None`.
///
/// ```
/// let qs = qstring::QString::from("?foo=bar");
/// let foo = &qs.get("panda");
/// assert!(foo.is_none());
/// ```
///
/// The query string can be assembled from pairs.
///
/// ```
/// let qs = qstring::QString::new(vec![
///    ("foo", "bar baz"),
///    ("panda", "true"),
/// ]);
/// assert_eq!(format!("{}", qs), "?foo=bar%20baz&panda=true");
/// ```
///
#[derive(Clone, Debug, PartialEq, Default)]
pub struct QString {
    pairs: Vec<(String, QValue)>,
}

#[derive(Clone, Debug, PartialEq)]
pub enum QValue {
    Empty,
    Value(String),
}

impl From<String> for QValue {
    fn from(s: String) -> QValue {
        QValue::Value(s)
    }
}

impl QString {
    /// Constructs a `QString` from a list of pairs.
    ///
    /// ```
    /// let qs = qstring::QString::new(vec![
    ///    ("foo", "bar baz"),
    ///    ("panda", "true"),
    /// ]);
    /// assert_eq!(format!("{}", qs), "?foo=bar%20baz&panda=true");
    /// ```
    pub fn new<S, T>(params: Vec<(S, T)>) -> QString
    where
        S: Into<String>,
        T: Into<String>,
    {
        QString {
            pairs: params
                .into_iter()
                .map(|(k, v)| (k.into(), QValue::Value(v.into())))
                .collect(),
        }
    }

    /// Tells if a query parameter is present.
    ///
    /// ```
    /// let qs = qstring::QString::from("?foo");
    /// assert!(qs.has("foo"));
    /// assert!(qs.get("foo").is_some());
    /// ```
    pub fn has(&self, name: &str) -> bool {
        println!("{:?}", self.pairs);
        self.pairs.iter().find(|&p| p.0 == name).is_some()
    }

    /// Get a query parameter by name.
    ///
    /// Empty query parameters return `""`
    ///
    /// ```
    /// let qs = qstring::QString::from("?foo=bar");
    /// let foo = qs.get("foo");
    /// assert_eq!(foo, Some("bar".to_string()));
    /// ```
    pub fn get(&self, name: &str) -> Option<String> {
        self.pairs
            .iter()
            .find(|&p| p.0 == name)
            .and_then(|ref p| match &p.1 {
                &QValue::Empty => Some("".to_string()),
                &QValue::Value(ref s) => Some(s.clone()),
            })
    }

    /// Converts the QString to list of pairs.
    ///
    /// ```
    /// let qs = qstring::QString::from("?foo=bar&baz=boo");
    /// let ps = qs.to_pairs();
    /// assert_eq!(ps, vec![
    ///     ("foo".to_string(), "bar".to_string()),
    ///     ("baz".to_string(), "boo".to_string()),
    /// ]);
    /// ```
    pub fn to_pairs(self) -> Vec<(String, String)> {
        self.pairs.iter().map(|p| (p.0.clone(), match &p.1 {
            &QValue::Empty => "".to_string(),
            &QValue::Value(ref s) => s.clone(),
        })).collect()
    }

    /// Adds another query parameter pair.
    ///
    /// ```
    /// let mut qs = qstring::QString::from("?foo=bar&baz=boo");
    ///
    /// qs.add_pair(("panda", "bear"));
    ///
    /// assert_eq!(qs.to_string(), "?foo=bar&baz=boo&panda=bear");
    /// ```
    pub fn add_pair<S, T>(&mut self, pair: (S, T))
    where
        S: Into<String>,
        T: Into<String>,
    {
        self.pairs.push((pair.0.into(), QValue::Value(pair.1.into())));
    }

    /// Parse the string and add all found parameters to this instance.
    ///
    /// ```
    /// let mut qs = qstring::QString::from("?foo");
    ///
    /// qs.add_str("&bar=baz&pooch&panda=bear");
    ///
    /// assert_eq!(qs.to_string(), "?foo&bar=baz&pooch&panda=bear");
    /// ```
    pub fn add_str(&mut self, origin: &str) {
        let mut to_add = str_to_pairs(origin);
        self.pairs.append(&mut to_add);
    }
}

impl<'a> From<&'a str> for QString {
    /// Constructs a new `QString` by parsing a query string part of the URL.
    /// Can start with ? or not, either works.
    ///
    /// Examples
    ///
    /// ```
    /// let qs = qstring::QString::from("?foo=bar");
    /// let v: Vec<(String, String)> = qs.to_pairs();
    /// assert_eq!(v, vec![("foo".to_string(), "bar".to_string())]);
    /// ```
    fn from(origin: &str) -> Self {
        QString {
            pairs: str_to_pairs(origin)
        }
    }
}

fn str_to_pairs(origin: &str) -> Vec<(String, QValue)> {
    // current slice left to find params in
    let mut cur = origin;

    // move forward if start with ?
    if cur.len() > 0 && &cur[0..1] == "?" {
        cur = &cur[1..];
    }

    // where we build found parameters into
    let mut params = vec![];

    while cur.len() > 0 {
        // if we're positioned on a &, skip it
        if &cur[0..1] == "&" {
            cur = &cur[1..];
            continue;
        }
        // find position of next =
        let (name, rest) = match cur.find("=") {
            // no next =, name will be until next & or until end
            None => match cur.find("&") {
                // no &, name is until end
                None => {
                    params.push((decode(&cur[..]), QValue::Empty));
                    break;
                },
                // name is until next &, which means no value and shortcut
                // to start straight after the &.
                Some(pos) => {
                    params.push((decode(&cur[..pos]), QValue::Empty));
                    cur = &cur[(pos + 1)..];
                    continue;
                }
            },
            // found one, name is up until = and rest is after.
            Some(pos) => (&cur[..pos], &cur[(pos + 1)..]),
        };
        // skip parameters with no name
        if name.len() == 0 {
            cur = rest;
            continue;
        }
        // from rest, find next occurence of &
        let (value, newcur) = match rest.find("&") {
            // no next &, then value is all up until end
            None => (rest, ""),
            // found one, value is up until & and next round starts after.
            Some(pos) => (&rest[..pos], &rest[(pos + 1)..]),
        };
        // found a parameter
        params.push((decode(name), QValue::Value(decode(value))));
        cur = newcur;
    }
    params
}

impl IntoIterator for QString {
    type Item = (String, String);
    type IntoIter = ::std::vec::IntoIter<(String, String)>;
    fn into_iter(self) -> Self::IntoIter {
        self.to_pairs().into_iter()
    }
}

impl Into<Vec<(String, String)>> for QString {
    fn into(self) -> Vec<(String, String)> {
        self.to_pairs()
    }
}

impl Into<String> for QString {
    fn into(self) -> String {
        format!("{}", self)
    }
}

impl ::std::fmt::Display for QString {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "?")?;
        for (idx, ref p) in self.pairs.iter().enumerate() {
            write!(
                f,
                "{}{}{}",
                (if idx == 0 { "" } else { "&" }),
                encode(&p.0),
                match &p.1 {
                    &QValue::Empty => "".to_string(),
                    &QValue::Value(ref s) => format!("={}", encode(s)),
                }
            )?;
        }
        Ok(())
    }
}

fn decode(s: &str) -> String {
    percent_decode(s.as_bytes())
        .decode_utf8()
        .map(|cow| cow.into_owned())
        .unwrap_or_else(|_| s.to_string())
}


fn encode(s: &str) -> String {
    utf8_percent_encode(s, QUERY_ENCODE_SET).to_string()
}


#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! test {
        ($func_name:ident, $origin:expr, $result:expr) => (
            #[test]
            fn $func_name() {
                let qs = QString::from($origin);
                let ps: Vec<(String, String)> = qs.to_pairs();
                let cs: Vec<(String, String)> = ($result as Vec<(&str, &str)>)
                    .into_iter().map(|(k,v)| (k.to_string(), v.to_string()))
                    .collect();
                assert_eq!(ps, cs);
            }
        )
    }

    test!(empty_1, "", vec![]);
    test!(empty_2, "?", vec![]);
    test!(empty_3, "&", vec![]);
    test!(empty_4, "=", vec![]);
    test!(empty_5, "?=", vec![]);
    test!(empty_6, "?&", vec![]);

    test!(a_is_1, "a", vec![("a", "")]);
    test!(a_is_2, "a=", vec![("a", "")]);
    test!(a_is_3, "a=b", vec![("a", "b")]);
    test!(a_is_4, "?a", vec![("a", "")]);
    test!(a_is_5, "?a=", vec![("a", "")]);
    test!(a_is_6, "?a=b", vec![("a", "b")]);
    test!(a_is_7, "?&a", vec![("a", "")]);
    test!(a_is_8, "?&a=", vec![("a", "")]);
    test!(a_is_9, "?&a=b", vec![("a", "b")]);
    test!(a_is_10, "?a=&", vec![("a", "")]);
    test!(a_is_11, "?=a", vec![("a", "")]);

    test!(a_is_eq_1, "a==", vec![("a", "=")]);

    test!(is_q_1, "??", vec![("?", "")]);
    test!(is_q_2, "&?", vec![("?", "")]);
    test!(is_q_3, "??a", vec![("?a", "")]);
    test!(is_q_4, "&?a", vec![("?a", "")]);

    test!(ac_is_1, "?a&c", vec![("a", ""), ("c", "")]);
    test!(ac_is_2, "?a&c&", vec![("a", ""), ("c", "")]);
    test!(ac_is_3, "?a=&c", vec![("a", ""), ("c", "")]);
    test!(ac_is_4, "?a=&c=", vec![("a", ""), ("c", "")]);
    test!(ac_is_5, "?a=b&c=", vec![("a", "b"), ("c", "")]);
    test!(ac_is_6, "?a=&c=d", vec![("a", ""), ("c", "d")]);
    test!(ac_is_7, "?a=b&c=d", vec![("a", "b"), ("c", "d")]);

}