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
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use unquote::unquote_plus;
pub type QueryValue = Vec<String>;
pub type Query = HashMap<String, QueryValue>;
pub trait GetQuery {
fn get_first(&self, k: &String) -> Option<&String>;
fn get_from_str(&self, k: &str) -> Option<QueryValue>;
fn get_first_from_str(&self, k: &str) -> Option<String>;
}
impl GetQuery for Query {
fn get_first(&self, k: &String) -> Option<&String> {
match self.get(k) {
Some(value) => value.get(0),
None => None,
}
}
fn get_from_str(&self, k: &str) -> Option<QueryValue> {
match self.get(&k.to_string()) {
Some(value) => Some(value.iter().map(|e| e.to_string()).collect()),
None => None,
}
}
fn get_first_from_str(&self, k: &str) -> Option<String> {
match self.get(&k.to_string()) {
Some(value) => match value.get(0) {
Some(string) => Some(string.to_string()),
None => None,
},
None => None,
}
}
}
pub fn parse_qs<S: AsRef<str>>(s: S) -> Query {
let mut map : Query = Query::new();
for item in s.as_ref().split(|c| c == '&' || c == ';') {
match item.find('=') {
Some(index) => {
let (key, value) = item.split_at(index);
let _key = match unquote_plus(key) {
Ok(k) => k,
Err(_) => continue,
};
let _value = match unquote_plus(value.trim_left_matches('=')) {
Ok(v) => v,
Err(_) => continue,
};
if _value.is_empty() {
continue;
}
let mut result = match map.entry(_key) {
Vacant(entry) => entry.insert(Vec::new()),
Occupied(entry) => entry.into_mut(),
};
result.push(_value);
},
None => continue,
}
}
return map;
}