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;
}