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
336
337
338
339
340
use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::fmt;
use std::iter::FromIterator;
use std::hash::{BuildHasher, Hash};
use std::rc::Rc;
use std::sync::Arc;

use serde::de;
use serde::Deserializer;

/// Allows access to the query parameters in an url or a body.
///
/// Use one of the listed implementations below. Since those may be a bit confusing due to their
/// abundant use of generics, basically use any type of `HashMap` that maps 'str-likes' to a
/// collection of other 'str-likes'. Popular instances may be:
/// * `HashMap<String, String>`
/// * `HashMap<String, Vec<String>>`
/// * `HashMap<Cow<'static, str>, Cow<'static, str>>`
///
/// You should generally not have to implement this trait yourself, and if you do there are
/// additional requirements on your implementation to guarantee standard conformance. Therefore the
/// trait is marked as `unsafe`.
pub unsafe trait QueryParameter {
    /// Get the **unique** value associated with a key.
    ///
    /// If there are multiple values, return `None`. This is very important to guarantee
    /// conformance to the RFC. Afaik it prevents potentially subverting validation middleware,
    /// order dependent processing, or simple confusion between different components who parse the
    /// query string from different ends.
    fn unique_value(&self, key: &str) -> Option<Cow<str>>;

    /// Guarantees that one can grab an owned copy.
    fn normalize(&self) -> NormalizedParameter;
}

/// The query parameter normal form.
///
/// When a request wants to give access to its query or body parameters by reference, it can do so
/// by a reference of the particular trait. But when the representation of the query is not stored
/// in the memory associated with the request, it needs to be allocated to outlive the borrow on
/// the request.  This allocation may as well perform the minimization/normalization into a
/// representation actually consumed by the backend. This normal form thus encapsulates the
/// associated `clone-into-normal form` by various possible constructors from references [WIP].
///
/// This gives rise to a custom `Cow<QueryParameter>` instance by requiring that normalization into
/// memory with unrelated lifetime is always possible.
///
/// Internally a hashmap but this may change due to optimizations.
#[derive(Clone, Debug, Default)]
pub struct NormalizedParameter {
    /// The value is `None` if the key appeared at least twice.
    inner: HashMap<Cow<'static, str>, Option<Cow<'static, str>>>,
}

unsafe impl QueryParameter for NormalizedParameter {
    fn unique_value(&self, key: &str) -> Option<Cow<str>> {
        self.inner
            .get(key)
            .and_then(|val| val.as_ref().map(Cow::as_ref).map(Cow::Borrowed))
    }

    fn normalize(&self) -> NormalizedParameter {
        self.clone()
    }
}

impl NormalizedParameter {
    /// Create an empty map.
    pub fn new() -> Self {
        NormalizedParameter::default()
    }

    /// Insert a key-value-pair or mark key as dead if already present.
    ///
    /// Since each key must appear at most once, we do not remove it from the map but instead mark
    /// the key as having a duplicate entry.
    pub fn insert_or_poison(&mut self, key: Cow<'static, str>, val: Cow<'static, str>) {
        let unique_val = Some(val);
        self.inner
            .entry(key)
            .and_modify(|val| *val = None)
            .or_insert(unique_val);
    }
}

impl Borrow<dyn QueryParameter> for NormalizedParameter {
    fn borrow(&self) -> &(dyn QueryParameter + 'static) {
        self
    }
}

impl Borrow<dyn QueryParameter + Send> for NormalizedParameter {
    fn borrow(&self) -> &(dyn QueryParameter + Send + 'static) {
        self
    }
}

impl<'de> de::Deserialize<'de> for NormalizedParameter {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct Visitor(NormalizedParameter);

        impl<'a> de::Visitor<'a> for Visitor {
            type Value = NormalizedParameter;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "a sequence of key-value-pairs")
            }

            fn visit_seq<A>(mut self, mut access: A) -> Result<Self::Value, A::Error>
            where
                A: de::SeqAccess<'a>,
            {
                while let Some((key, value)) = access.next_element::<(String, String)>()? {
                    self.0.insert_or_poison(key.into(), value.into())
                }

                Ok(self.0)
            }
        }

        let visitor = Visitor(NormalizedParameter::default());
        deserializer.deserialize_seq(visitor)
    }
}

impl<K, V> FromIterator<(K, V)> for NormalizedParameter
where
    K: Into<Cow<'static, str>>,
    V: Into<Cow<'static, str>>,
{
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = (K, V)>,
    {
        let mut target = NormalizedParameter::default();
        iter.into_iter()
            .for_each(|(k, v)| target.insert_or_poison(k.into(), v.into()));
        target
    }
}

impl ToOwned for dyn QueryParameter {
    type Owned = NormalizedParameter;

    fn to_owned(&self) -> Self::Owned {
        self.normalize()
    }
}

impl ToOwned for dyn QueryParameter + Send {
    type Owned = NormalizedParameter;

    fn to_owned(&self) -> Self::Owned {
        self.normalize()
    }
}

/// Return a reference to value in a collection if it is the only one.
///
/// For example, a vector of string like types returns a reference to its first
/// element if there are no other, else it returns `None`.
///
/// If this were done with slices, that would require choosing a particular
/// value type of the underlying slice e.g. `[String]`.
pub unsafe trait UniqueValue {
    /// Borrow the unique value reference.
    fn get_unique(&self) -> Option<&str>;
}

unsafe impl<K, V, S: BuildHasher> QueryParameter for HashMap<K, V, S>
where
    K: Borrow<str> + Eq + Hash,
    V: UniqueValue + Eq + Hash,
{
    fn unique_value(&self, key: &str) -> Option<Cow<str>> {
        self.get(key).and_then(V::get_unique).map(Cow::Borrowed)
    }

    fn normalize(&self) -> NormalizedParameter {
        let inner = self
            .iter()
            .filter_map(|(key, val)| {
                val.get_unique().map(|value| {
                    (
                        Cow::Owned(key.borrow().to_string()),
                        Some(Cow::Owned(value.to_string())),
                    )
                })
            })
            .collect();

        NormalizedParameter { inner }
    }
}

unsafe impl<K, V> QueryParameter for Vec<(K, V)>
where
    K: Borrow<str> + Eq + Hash,
    V: Borrow<str> + Eq + Hash,
{
    fn unique_value(&self, key: &str) -> Option<Cow<str>> {
        let mut value = None;

        for entry in self.iter() {
            if entry.0.borrow() == key {
                if value.is_some() {
                    return None;
                }
                value = Some(Cow::Borrowed(entry.1.borrow()));
            }
        }

        value
    }

    fn normalize(&self) -> NormalizedParameter {
        let mut params = NormalizedParameter::default();
        self.iter()
            .map(|&(ref key, ref val)| {
                (
                    Cow::Owned(key.borrow().to_string()),
                    Cow::Owned(val.borrow().to_string()),
                )
            })
            .for_each(|(key, val)| params.insert_or_poison(key, val));
        params
    }
}

unsafe impl<'a, Q: QueryParameter + 'a + ?Sized> QueryParameter for &'a Q {
    fn unique_value(&self, key: &str) -> Option<Cow<str>> {
        (**self).unique_value(key)
    }

    fn normalize(&self) -> NormalizedParameter {
        (**self).normalize()
    }
}

unsafe impl<'a, Q: QueryParameter + 'a + ?Sized> QueryParameter for &'a mut Q {
    fn unique_value(&self, key: &str) -> Option<Cow<str>> {
        (**self).unique_value(key)
    }

    fn normalize(&self) -> NormalizedParameter {
        (**self).normalize()
    }
}

unsafe impl UniqueValue for str {
    fn get_unique(&self) -> Option<&str> {
        Some(self)
    }
}

unsafe impl UniqueValue for String {
    fn get_unique(&self) -> Option<&str> {
        Some(&self)
    }
}

unsafe impl<'a, V> UniqueValue for &'a V
where
    V: AsRef<str> + ?Sized,
{
    fn get_unique(&self) -> Option<&str> {
        Some(self.as_ref())
    }
}

unsafe impl<'a> UniqueValue for Cow<'a, str> {
    fn get_unique(&self) -> Option<&str> {
        Some(self.as_ref())
    }
}

unsafe impl<V: UniqueValue> UniqueValue for Option<V> {
    fn get_unique(&self) -> Option<&str> {
        self.as_ref().and_then(V::get_unique)
    }
}

unsafe impl<V: UniqueValue> UniqueValue for [V] {
    fn get_unique(&self) -> Option<&str> {
        if self.len() > 1 {
            None
        } else {
            self.get(0).and_then(V::get_unique)
        }
    }
}

unsafe impl<V: UniqueValue + ?Sized> UniqueValue for Box<V> {
    fn get_unique(&self) -> Option<&str> {
        (**self).get_unique()
    }
}

unsafe impl<V: UniqueValue + ?Sized> UniqueValue for Rc<V> {
    fn get_unique(&self) -> Option<&str> {
        (**self).get_unique()
    }
}

unsafe impl<V: UniqueValue + ?Sized> UniqueValue for Arc<V> {
    fn get_unique(&self) -> Option<&str> {
        (**self).get_unique()
    }
}

unsafe impl<V: UniqueValue> UniqueValue for Vec<V> {
    fn get_unique(&self) -> Option<&str> {
        if self.len() > 1 {
            None
        } else {
            self.get(0).and_then(V::get_unique)
        }
    }
}

mod test {
    use super::*;

    /// Compilation tests for various possible QueryParameter impls.
    #[allow(unused)]
    #[allow(dead_code)]
    fn test_query_parameter_impls() {
        let _ = (&HashMap::<String, String>::new()) as &dyn QueryParameter;
        let _ = (&HashMap::<&'static str, &'static str>::new()) as &dyn QueryParameter;
        let _ = (&HashMap::<Cow<'static, str>, Cow<'static, str>>::new()) as &dyn QueryParameter;

        let _ = (&HashMap::<String, Vec<String>>::new()) as &dyn QueryParameter;
        let _ = (&HashMap::<String, Box<String>>::new()) as &dyn QueryParameter;
        let _ = (&HashMap::<String, Box<[Cow<'static, str>]>>::new()) as &dyn QueryParameter;
    }
}