ttpkit-url 0.1.1

URL parsing and manipulation utilities for ttpkit.
Documentation
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! Query string parsing and serialization.

use std::{
    borrow::{Borrow, Cow},
    fmt::{self, Display, Formatter},
    ops::Deref,
    str::{FromStr, Utf8Error},
};

/// QueryDict key.
#[derive(Debug, Clone)]
pub struct QueryDictKey {
    inner: Cow<'static, str>,
}

impl QueryDictKey {
    /// Create a new key from a given static string.
    #[inline]
    pub const fn from_static(inner: &'static str) -> Self {
        Self {
            inner: Cow::Borrowed(inner),
        }
    }

    /// Create a new key from a given string.
    pub fn new<T>(key: T) -> Self
    where
        T: Into<String>,
    {
        Self {
            inner: Cow::Owned(key.into()),
        }
    }
}

impl AsRef<str> for QueryDictKey {
    #[inline]
    fn as_ref(&self) -> &str {
        &self.inner
    }
}

impl Borrow<str> for QueryDictKey {
    #[inline]
    fn borrow(&self) -> &str {
        &self.inner
    }
}

impl Deref for QueryDictKey {
    type Target = str;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl PartialEq for QueryDictKey {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.inner.eq_ignore_ascii_case(&other.inner)
    }
}

impl Eq for QueryDictKey {}

impl PartialEq<str> for QueryDictKey {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        self.inner.eq_ignore_ascii_case(other)
    }
}

impl PartialEq<QueryDictKey> for str {
    #[inline]
    fn eq(&self, other: &QueryDictKey) -> bool {
        self.eq_ignore_ascii_case(&other.inner)
    }
}

impl From<&'static str> for QueryDictKey {
    #[inline]
    fn from(key: &'static str) -> Self {
        Self::from_static(key)
    }
}

impl From<String> for QueryDictKey {
    #[inline]
    fn from(key: String) -> Self {
        Self::new(key)
    }
}

/// QueryDict value.
#[derive(Debug, Clone)]
pub struct QueryDictValue {
    inner: Cow<'static, str>,
}

impl QueryDictValue {
    /// Create a new value from a given static string.
    #[inline]
    pub const fn from_static(inner: &'static str) -> Self {
        Self {
            inner: Cow::Borrowed(inner),
        }
    }

    /// Create a new value from a given string.
    pub fn new<T>(key: T) -> Self
    where
        T: Into<String>,
    {
        Self {
            inner: Cow::Owned(key.into()),
        }
    }
}

impl AsRef<str> for QueryDictValue {
    #[inline]
    fn as_ref(&self) -> &str {
        &self.inner
    }
}

impl Borrow<str> for QueryDictValue {
    #[inline]
    fn borrow(&self) -> &str {
        &self.inner
    }
}

impl Deref for QueryDictValue {
    type Target = str;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl From<&'static str> for QueryDictValue {
    #[inline]
    fn from(key: &'static str) -> Self {
        Self::from_static(key)
    }
}

impl From<String> for QueryDictValue {
    #[inline]
    fn from(key: String) -> Self {
        Self::new(key)
    }
}

/// QueryDict item.
#[derive(Debug, Clone)]
pub struct QueryDictItem {
    key: QueryDictKey,
    value: Option<QueryDictValue>,
}

impl QueryDictItem {
    /// Get the item key.
    #[inline]
    pub fn key(&self) -> &QueryDictKey {
        &self.key
    }

    /// Get the item value.
    #[inline]
    pub fn value(&self) -> Option<&QueryDictValue> {
        self.value.as_ref()
    }
}

impl<K> From<(K,)> for QueryDictItem
where
    K: Into<QueryDictKey>,
{
    fn from(item: (K,)) -> Self {
        let (key,) = item;

        Self {
            key: key.into(),
            value: None,
        }
    }
}

impl<K, V> From<(K, V)> for QueryDictItem
where
    K: Into<QueryDictKey>,
    V: Into<QueryDictValue>,
{
    fn from(item: (K, V)) -> Self {
        let (key, value) = item;

        Self {
            key: key.into(),
            value: Some(value.into()),
        }
    }
}

impl Display for QueryDictItem {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        let key = crate::url_encode(self.key.as_ref());

        if let Some(value) = self.value.as_ref() {
            let value = crate::url_encode(value.as_ref());

            write!(f, "{key}={value}")
        } else {
            write!(f, "{key}")
        }
    }
}

impl FromStr for QueryDictItem {
    type Err = Utf8Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (key, value) = s
            .split_once('=')
            .map(|(k, v)| (k, Some(v)))
            .unwrap_or((s, None));

        let key = String::from_utf8(Cow::into_owned(crate::url_decode(key)))
            .map_err(|err| err.utf8_error())?
            .into();

        let value = value
            .map(crate::url_decode)
            .map(|decoded| String::from_utf8(decoded.into_owned()))
            .transpose()
            .map_err(|err| err.utf8_error())?
            .map(QueryDictValue::from);

        let item = Self { key, value };

        Ok(item)
    }
}

/// QueryDict.
///
/// This type can be used to parse and serialize URL query strings.
///
/// The QueryDict uses `Vec<_>` internally to store the items, so it preserves
/// the item order and allows multiple items with the same key. This also means
/// that complexity of some operations is `O(n)`. However, this should not pose
/// a problem in practice, as the number of query parameters is usually small.
///  It is a trade-off between performance and footprint.
#[derive(Clone)]
pub struct QueryDict {
    items: Vec<QueryDictItem>,
}

impl QueryDict {
    /// Create a new instance of QueryDict.
    #[inline]
    pub const fn new() -> Self {
        Self { items: Vec::new() }
    }

    /// Create a new instance of QueryDict with a given initial capacity.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            items: Vec::with_capacity(capacity),
        }
    }

    /// Add a given item.
    ///
    /// This is an `O(1)` operation.
    pub fn add<T>(&mut self, item: T)
    where
        T: Into<QueryDictItem>,
    {
        self.items.push(item.into());
    }

    /// Replace all items having the same name (if any).
    ///
    /// This is an `O(n)` operation.
    pub fn set<T>(&mut self, item: T)
    where
        T: Into<QueryDictItem>,
    {
        // helper function preventing expensive monomorphizations
        fn inner(items: &mut Vec<QueryDictItem>, item: QueryDictItem) {
            items.retain(|i| !i.key.eq_ignore_ascii_case(&item.key));
            items.push(item);
        }

        inner(&mut self.items, item.into());
    }

    /// Remove all items with a given key.
    ///
    /// This is an `O(n)` operation.
    pub fn remove<N>(&mut self, key: &N)
    where
        N: AsRef<str> + ?Sized,
    {
        // helper function preventing expensive monomorphizations
        fn inner(fields: &mut Vec<QueryDictItem>, key: &str) {
            fields.retain(|i| !i.key.eq_ignore_ascii_case(key));
        }

        inner(&mut self.items, key.as_ref());
    }

    /// Get header fields with a given key.
    ///
    /// This is an `O(n)` operation.
    pub fn get<'a, N>(&'a self, key: &'a N) -> KeyIter<'a>
    where
        N: AsRef<str> + ?Sized,
    {
        KeyIter {
            inner: self.all(),
            key: key.as_ref(),
        }
    }

    /// Get the last item with a given key.
    ///
    /// This is an `O(n)` operation.
    pub fn last<'a, N>(&'a self, key: &'a N) -> Option<&'a QueryDictItem>
    where
        N: AsRef<str> + ?Sized,
    {
        // helper function to avoid expensive monomorphizations
        fn inner<'a>(iter: &mut KeyIter<'a>) -> Option<&'a QueryDictItem> {
            iter.next_back()
        }

        inner(&mut self.get(key))
    }

    /// Get value of the last item with a given key.
    ///
    /// This is an `O(n)` operation.
    pub fn last_value<'a, N>(&'a self, key: &'a N) -> Option<&'a QueryDictValue>
    where
        N: AsRef<str> + ?Sized,
    {
        // helper function to avoid expensive monomorphizations
        fn inner<'a>(iter: &mut KeyIter<'a>) -> Option<&'a QueryDictValue> {
            iter.next_back().and_then(|item| item.value())
        }

        inner(&mut self.get(key))
    }

    /// Get all items.
    #[inline]
    pub fn all(&self) -> Iter<'_> {
        Iter {
            inner: self.items.iter(),
        }
    }

    /// Check if the collection is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Get the number of items in the collection.
    #[inline]
    pub fn len(&self) -> usize {
        self.items.len()
    }
}

impl Default for QueryDict {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Display for QueryDict {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        let mut iter = self.items.iter();

        if let Some(item) = iter.next() {
            write!(f, "{item}")?;
        }

        for item in iter {
            write!(f, "&{item}")?;
        }

        Ok(())
    }
}

impl From<Vec<QueryDictItem>> for QueryDict {
    #[inline]
    fn from(items: Vec<QueryDictItem>) -> Self {
        Self { items }
    }
}

impl FromStr for QueryDict {
    type Err = Utf8Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut res = Self::new();

        for item in s.split('&') {
            let item = item.trim();

            if item.is_empty() {
                continue;
            }

            res.add(QueryDictItem::from_str(item)?);
        }

        Ok(res)
    }
}

/// QueryDict item iterator.
pub struct Iter<'a> {
    inner: std::slice::Iter<'a, QueryDictItem>,
}

impl<'a> Iterator for Iter<'a> {
    type Item = &'a QueryDictItem;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl<'a> DoubleEndedIterator for Iter<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back()
    }
}

impl<'a> ExactSizeIterator for Iter<'a> {
    #[inline]
    fn len(&self) -> usize {
        self.inner.len()
    }
}

/// QueryDict item iterator.
pub struct KeyIter<'a> {
    inner: Iter<'a>,
    key: &'a str,
}

impl<'a> Iterator for KeyIter<'a> {
    type Item = &'a QueryDictItem;

    fn next(&mut self) -> Option<Self::Item> {
        #[allow(clippy::while_let_on_iterator)]
        while let Some(item) = self.inner.next() {
            if item.key.eq_ignore_ascii_case(self.key) {
                return Some(item);
            }
        }

        None
    }
}

impl<'a> DoubleEndedIterator for KeyIter<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        while let Some(item) = self.inner.next_back() {
            if item.key.eq_ignore_ascii_case(self.key) {
                return Some(item);
            }
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use std::{borrow::Borrow, str::FromStr};

    use super::{QueryDict, QueryDictValue};

    fn qd_value_eq<A, B>(a: A, b: B) -> bool
    where
        A: Borrow<QueryDictValue>,
        B: Borrow<QueryDictValue>,
    {
        let a = a.borrow();
        let b = b.borrow();

        a.as_ref() == b.as_ref()
    }

    fn qd_values_eq<A, B>(a: A, b: B) -> bool
    where
        A: AsRef<[QueryDictValue]>,
        B: AsRef<[QueryDictValue]>,
    {
        let a = a.as_ref();
        let b = b.as_ref();

        a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| qd_value_eq(a, b))
    }

    #[test]
    fn test_query_dict_from_string() {
        let inputs = &[
            "sss",
            "aa=bb",
            "aa=bb&cc=dd",
            "aa=bb&aa=cc",
            "email=some%40example%2Ecom",
        ];

        for item in inputs {
            let dict = QueryDict::from_str(item);

            assert!(dict.is_ok());

            assert_eq!(format!("{}", dict.unwrap()), item.to_string());
        }
    }

    #[test]
    fn test_multiple_values() {
        let mut dict = QueryDict::default();

        dict.add(("slot", "first"));
        dict.add(("slot", "second"));

        assert_eq!(dict.last_value("slot").map(|v| v.as_ref()), Some("second"));

        assert!(qd_values_eq(
            dict.get("slot")
                .filter_map(|e| e.value())
                .cloned()
                .collect::<Vec<_>>(),
            vec![
                QueryDictValue::from("first"),
                QueryDictValue::from("second")
            ]
        ));
    }

    #[test]
    fn test_multiple_values_from_string() {
        let dict = QueryDict::from_str("bb[]=1&bb[]=2&&cc[]=3&bb[]=4").unwrap();

        assert!(qd_values_eq(
            dict.get("bb[]")
                .filter_map(|e| e.value())
                .cloned()
                .collect::<Vec<_>>(),
            vec![
                QueryDictValue::from("1"),
                QueryDictValue::from("2"),
                QueryDictValue::from("4"),
            ]
        ));
    }

    #[test]
    fn test_percent_decoding() {
        let dict = QueryDict::from_str("email=some%40example%2Ecom").unwrap();

        assert_eq!(
            dict.last_value("email").map(|v| v.as_ref()),
            Some("some@example.com")
        );
    }

    #[test]
    fn test_percent_encoding() {
        let mut dict = QueryDict::new();

        dict.add(("email", "some@example.com"));

        assert_eq!(dict.to_string(), String::from("email=some%40example%2Ecom"));
    }

    #[test]
    fn test_space_in_query() {
        let dict = QueryDict::from_str("a=%20x%20z%20&b=y").unwrap();

        assert_eq!(dict.last_value("a").map(|v| v.as_ref()), Some(" x z "));
    }

    #[test]
    fn test_remove() {
        let mut dict = QueryDict::from_str("bb[]=1&bb[]=2&cc[]=3&bb[]=4").unwrap();

        assert_eq!(dict.get("bb[]").count(), 3);
        assert_eq!(dict.all().count(), 4);

        dict.remove("bb[]");

        assert_eq!(dict.get("bb[]").count(), 0);
        assert_eq!(dict.all().count(), 1);
    }

    #[test]
    fn test_set() {
        let mut dict = QueryDict::from_str("bb[]=1&bb[]=2&cc[]=3&bb[]=4").unwrap();

        assert_eq!(dict.get("bb[]").count(), 3);
        assert_eq!(dict.all().count(), 4);

        dict.set(("bb[]", "5"));

        assert_eq!(dict.get("bb[]").count(), 1);
        assert_eq!(dict.all().count(), 2);
    }
}