oni_comb_uri_rs/models/
query.rs1use std::cmp::Ordering;
2use std::collections::HashMap;
3use std::fmt::Formatter;
4
5#[derive(Debug, Clone, PartialEq, Hash)]
6pub struct Query {
7 params: Vec<(String, Option<String>)>,
8}
9
10impl Default for Query {
11 fn default() -> Self {
12 Query { params: Vec::default() }
13 }
14}
15
16impl PartialOrd for Query {
17 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
18 self.to_string().partial_cmp(&other.to_string())
19 }
20}
21
22impl std::fmt::Display for Query {
23 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
24 write!(f, "{}", self.as_string())
25 }
26}
27
28impl From<Vec<(String, Option<String>)>> for Query {
29 fn from(src: Vec<(String, Option<String>)>) -> Self {
30 let params = src.into_iter().collect::<Vec<_>>();
31 Self { params }
32 }
33}
34
35impl From<Vec<(&str, Option<&str>)>> for Query {
36 fn from(src: Vec<(&str, Option<&str>)>) -> Self {
37 let params = src
38 .into_iter()
39 .map(|(k, v)| (k.to_string(), v.map(|v| v.to_string())))
40 .collect::<Vec<_>>();
41 Self { params }
42 }
43}
44
45impl Query {
46 pub fn new(params: Vec<(String, Option<String>)>) -> Self {
47 Self { params }
48 }
49
50 pub fn params(&self) -> HashMap<&String, Vec<&String>> {
51 let mut result: HashMap<&String, Vec<&String>> = HashMap::new();
52 for (key, value) in self.params.iter() {
53 match (result.get_mut(&key), value) {
54 (None, None) => {
55 result.insert(key, Vec::new());
56 }
57 (None, Some(v)) => {
58 result.insert(key, vec![v]);
59 }
60 (Some(values), Some(v)) => {
61 values.push(v);
62 }
63 _ => (),
64 }
65 }
66 result
67 }
68
69 pub fn add(&mut self, key: String, value: String) {
70 self.params.push((key, Some(value)));
71 }
72
73 pub fn add_opt(&mut self, key: String, value: Option<String>) {
74 match value {
75 Some(v) => {
76 self.add(key, v);
77 ()
78 }
79 None => (),
80 }
81 }
82
83 pub fn get_param(&self, key: String) -> Option<Vec<&String>> {
84 self.params().get(&key).map(|v| v.clone())
85 }
86
87 pub fn as_string(&self) -> String {
88 self
89 .params
90 .iter()
91 .map(|(k, v)| {
92 if v.is_none() {
93 k.clone()
94 } else {
95 format!(
96 "{}{}",
97 k,
98 v.as_ref().map(|s| format!("={}", s)).unwrap_or("".to_string())
99 )
100 }
101 })
102 .collect::<Vec<_>>()
103 .join("&")
104 }
105}