query-string-builder 0.6.0

A query string builder for percent encoding key-value pairs
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
use std::fmt;
use std::fmt::{Debug, Display, Formatter, Write};

use crate::QUERY;
use percent_encoding::utf8_percent_encode;

/// A type alias for the [`WrappedQueryString`] root.
pub type QueryStringSimple = WrappedQueryString<RootMarker, EmptyValue>;

/// A query string builder for percent encoding key-value pairs.
/// This variant reduces string allocations as much as possible, defers them to the
/// time of actual rendering, and is capable of storing references.
///
/// ## Example
///
/// ```
/// use query_string_builder::QueryString;
///
/// let weight: &f32 = &99.9;
///
/// let qs = QueryString::simple()
///             .with_value("q", "apple")
///             .with_value("category", "fruits and vegetables")
///             .with_opt_value("weight", Some(weight));
///
/// assert_eq!(
///     format!("https://example.com/{qs}"),
///     "https://example.com/?q=apple&category=fruits%20and%20vegetables&weight=99.9"
/// );
/// ```
pub struct WrappedQueryString<B, T>
where
    B: ConditionalDisplay + Identifiable,
    T: Display,
{
    base: BaseOption<B>,
    value: KvpOption<T>,
}

impl Default for QueryStringSimple {
    fn default() -> Self {
        QueryStringSimple::new()
    }
}

/// A helper type to track the values of [`WrappedQueryString`].
pub struct Kvp<K, V>
where
    K: Display,
    V: Display,
{
    key: K,
    value: V,
}

enum BaseOption<B> {
    Some(B),
    None,
}

enum KvpOption<T> {
    Some(T),
    None,
}

/// This type serves as a root marker for the builder. It has no public constructor,
/// thus can only be created within this crate.
pub struct RootMarker(());

/// This type serves as an empty value marker for the builder. It has no public constructor,
/// thus can only be created within this crate.
pub struct EmptyValue(());

impl<B, T> WrappedQueryString<B, T>
where
    B: ConditionalDisplay + Identifiable,
    T: Display,
{
    /// Creates a new, empty query string builder.
    pub(crate) fn new() -> WrappedQueryString<RootMarker, EmptyValue> {
        WrappedQueryString {
            base: BaseOption::None,
            value: KvpOption::None,
        }
    }

    /// Appends a key-value pair to the query string.
    ///
    /// ## Example
    ///
    /// ```
    /// use query_string_builder::QueryString;
    ///
    /// let qs = QueryString::dynamic()
    ///             .with_value("q", "🍎 apple")
    ///             .with_value("category", "fruits and vegetables")
    ///             .with_value("answer", 42);
    ///
    /// assert_eq!(
    ///     format!("https://example.com/{qs}"),
    ///     "https://example.com/?q=%F0%9F%8D%8E%20apple&category=fruits%20and%20vegetables&answer=42"
    /// );
    /// ```
    pub fn with_value<K: Display, V: Display>(
        self,
        key: K,
        value: V,
    ) -> WrappedQueryString<Self, Kvp<K, V>> {
        WrappedQueryString {
            base: BaseOption::Some(self),
            value: KvpOption::Some(Kvp { key, value }),
        }
    }

    /// Appends a key-value pair to the query string if the value exists.
    ///
    /// ## Example
    ///
    /// ```
    /// use query_string_builder::QueryString;
    ///
    /// let qs = QueryString::dynamic()
    ///             .with_opt_value("q", Some("🍎 apple"))
    ///             .with_opt_value("f", None::<String>)
    ///             .with_opt_value("category", Some("fruits and vegetables"))
    ///             .with_opt_value("works", Some(true));
    ///
    /// assert_eq!(
    ///     format!("https://example.com/{qs}"),
    ///     "https://example.com/?q=%F0%9F%8D%8E%20apple&category=fruits%20and%20vegetables&works=true"
    /// );
    /// ```
    pub fn with_opt_value<K: Display, V: Display>(
        self,
        key: K,
        value: Option<V>,
    ) -> WrappedQueryString<Self, Kvp<K, V>> {
        if let Some(value) = value {
            WrappedQueryString {
                base: BaseOption::Some(self),
                value: KvpOption::Some(Kvp { key, value }),
            }
        } else {
            WrappedQueryString {
                base: BaseOption::Some(self),
                value: KvpOption::None,
            }
        }
    }

    /// Determines the number of key-value pairs currently in the builder.
    pub fn len(&self) -> usize {
        if self.is_empty() {
            return 0;
        }

        1 + self.base.len()
    }

    /// Determines if the builder is currently empty.
    pub fn is_empty(&self) -> bool {
        // If this is the root node, and we don't have a value, we're empty.
        if self.is_root() && self.value.is_empty() {
            return true;
        }

        // If we're not the root node we need to check if all values are empty.
        if !self.value.is_empty() {
            return false;
        }

        self.base.is_empty()
    }
}

pub trait Identifiable {
    fn is_root(&self) -> bool;
    fn is_empty(&self) -> bool;
    fn len(&self) -> usize;
}

pub trait ConditionalDisplay {
    fn cond_fmt(&self, should_display: bool, f: &mut Formatter<'_>) -> Result<usize, fmt::Error>;
}

impl Identifiable for RootMarker {
    fn is_root(&self) -> bool {
        unreachable!()
    }

    fn is_empty(&self) -> bool {
        unreachable!()
    }

    fn len(&self) -> usize {
        unreachable!()
    }
}

impl ConditionalDisplay for RootMarker {
    fn cond_fmt(&self, _should_display: bool, _f: &mut Formatter<'_>) -> Result<usize, fmt::Error> {
        unreachable!()
    }
}

impl Display for RootMarker {
    fn fmt(&self, _f: &mut Formatter<'_>) -> fmt::Result {
        unreachable!()
    }
}

impl<B> ConditionalDisplay for BaseOption<B>
where
    B: ConditionalDisplay,
{
    fn cond_fmt(&self, should_display: bool, f: &mut Formatter<'_>) -> Result<usize, fmt::Error> {
        match self {
            BaseOption::Some(base) => Ok(base.cond_fmt(should_display, f)?),
            BaseOption::None => {
                // Reached the root marker.
                if should_display {
                    f.write_char('?')?;
                }
                Ok(0)
            }
        }
    }
}

impl<B, T> ConditionalDisplay for WrappedQueryString<B, T>
where
    B: ConditionalDisplay + Identifiable,
    T: Display,
{
    fn cond_fmt(&self, should_display: bool, f: &mut Formatter<'_>) -> Result<usize, fmt::Error> {
        let depth = if !should_display {
            // Our caller had nothing to display. If we have nothing to display either,
            // we move on to our parent.
            if self.value.is_empty() {
                return self.base.cond_fmt(false, f);
            }

            // We do have things to display - render the parent!
            self.base.cond_fmt(true, f)?
        } else {
            // The caller has things to display - go ahead regardless.
            self.base.cond_fmt(true, f)?
        };

        // If we have nothing to render, return the known depth.
        if self.value.is_empty() {
            return Ok(depth);
        }

        // Display and increase the depth.
        self.value.fmt(f)?;

        // If our parent indicated content was displayable, add the combinator.
        if should_display {
            f.write_char('&')?;
        }

        Ok(depth + 1)
    }
}

impl<B> BaseOption<B>
where
    B: Identifiable + ConditionalDisplay,
{
    fn is_empty(&self) -> bool {
        match self {
            BaseOption::Some(value) => value.is_empty(),
            BaseOption::None => true,
        }
    }

    fn len(&self) -> usize {
        match self {
            BaseOption::Some(value) => value.len(),
            BaseOption::None => 0,
        }
    }
}

impl<B, T> Identifiable for WrappedQueryString<B, T>
where
    B: ConditionalDisplay + Identifiable,
    T: Display,
{
    fn is_root(&self) -> bool {
        match self.base {
            BaseOption::Some(_) => false,
            BaseOption::None => true,
        }
    }

    fn is_empty(&self) -> bool {
        match self.value {
            KvpOption::Some(_) => false,
            KvpOption::None => self.base.is_empty(),
        }
    }

    fn len(&self) -> usize {
        match self.value {
            KvpOption::Some(_) => 1 + self.base.len(),
            KvpOption::None => self.base.len(),
        }
    }
}

impl<T> KvpOption<T> {
    fn is_empty(&self) -> bool {
        match self {
            KvpOption::Some(_) => false,
            KvpOption::None => true,
        }
    }
}

impl Display for EmptyValue {
    fn fmt(&self, _f: &mut Formatter<'_>) -> fmt::Result {
        Ok(())
    }
}

impl<T> Display for BaseOption<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            BaseOption::Some(d) => Display::fmt(d, f),
            BaseOption::None => Ok(()),
        }
    }
}

impl<T> Display for KvpOption<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            KvpOption::Some(d) => Display::fmt(d, f),
            KvpOption::None => Ok(()),
        }
    }
}

impl<K, V> Display for Kvp<K, V>
where
    K: Display,
    V: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(&utf8_percent_encode(&self.key.to_string(), QUERY), f)?;
        f.write_char('=')?;
        Display::fmt(&utf8_percent_encode(&self.value.to_string(), QUERY), f)
    }
}

impl<B, T> Display for WrappedQueryString<B, T>
where
    B: ConditionalDisplay + Identifiable,
    T: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let should_display = !self.value.is_empty();

        self.base.cond_fmt(should_display, f)?;
        if should_display {
            Display::fmt(&self.value, f)?;
        }

        Ok(())
    }
}

impl<B, T> Debug for WrappedQueryString<B, T>
where
    B: ConditionalDisplay + Identifiable,
    T: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(self, f)
    }
}

#[cfg(test)]
mod tests {
    use crate::slim::{BaseOption, EmptyValue, KvpOption};
    use crate::QueryString;

    #[test]
    fn test_empty() {
        let qs = QueryString::simple();

        assert!(qs.is_empty());
        assert_eq!(qs.len(), 0);

        assert_eq!(qs.to_string(), "");
    }

    #[test]
    fn test_empty_complex() {
        let qs = QueryString::simple().with_opt_value("key", None::<&str>);

        assert!(qs.is_empty());
        assert_eq!(qs.len(), 0);

        assert_eq!(qs.to_string(), "");
    }

    #[test]
    fn test_simple() {
        let apple = "apple???";

        let qs = QueryString::simple()
            .with_value("q", &apple)
            .with_value("category", "fruits and vegetables")
            .with_value("tasty", true)
            .with_value("weight", 99.9);

        assert!(!qs.is_empty());
        assert_eq!(qs.len(), 4);

        assert_eq!(
            format!("{qs}"),
            "?q=apple???&category=fruits%20and%20vegetables&tasty=true&weight=99.9"
        );
    }

    #[test]
    fn test_encoding() {
        let qs = QueryString::simple()
            .with_value("q", "Grünkohl")
            .with_value("category", "Gemüse");

        assert!(!qs.is_empty());
        assert_eq!(qs.len(), 2);

        assert_eq!(qs.to_string(), "?q=Gr%C3%BCnkohl&category=Gem%C3%BCse");
    }

    #[test]
    fn test_emoji() {
        let qs = QueryString::simple()
            .with_value("q", "🥦")
            .with_value("🍽️", "🍔🍕");

        assert!(!qs.is_empty());
        assert_eq!(qs.len(), 2);

        assert_eq!(
            format!("{qs:?}"),
            "?q=%F0%9F%A5%A6&%F0%9F%8D%BD%EF%B8%8F=%F0%9F%8D%94%F0%9F%8D%95"
        );
    }

    #[test]
    fn test_optional() {
        let qs = QueryString::simple()
            .with_value("q", "celery")
            .with_opt_value("taste", None::<String>)
            .with_opt_value("category", Some("fruits and vegetables"))
            .with_opt_value("tasty", Some(true))
            .with_opt_value("weight", Some(99.9));

        assert!(!qs.is_empty());
        assert_eq!(qs.len(), 4);

        assert_eq!(
            qs.to_string(),
            "?q=celery&category=fruits%20and%20vegetables&tasty=true&weight=99.9"
        );
        assert_eq!(qs.len(), 4); // not five!
    }

    #[test]
    fn test_display() {
        assert_eq!(format!("{}", KvpOption::<i32>::None), "");
        assert_eq!(format!("{}", BaseOption::<i32>::None), "");
        assert_eq!(format!("{}", EmptyValue(())), "");
    }
}