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
//! A URI query/`x-www-form-urlencoded` string serializer.

use std::fmt::Write;

use crate::util::PercentEncode;

use super::Serializer;

/// A `Serializer` that produces a URI query or an `x-www-form-urlencoded` string from a request.
pub struct Urlencoder {
    data: String,
    next_append: Append,
}

enum Append {
    None,
    Question,
    Ampersand,
}

impl Urlencoder {
    /// Creates a `Urlencoder` that produces an `x-www-form-urlencoded` string.
    pub fn form() -> Self {
        Urlencoder {
            data: String::new(),
            next_append: Append::None,
        }
    }

    /// Creates a `Urlencoder` that appends a query part to the given URI.
    pub fn query(uri: String) -> Self {
        Urlencoder {
            data: uri,
            next_append: Append::Question,
        }
    }

    fn append_delim(&mut self) {
        match self.next_append {
            Append::None => self.next_append = Append::Ampersand,
            Append::Question => {
                self.data.push('?');
                self.next_append = Append::Ampersand;
            }
            Append::Ampersand => self.data.push('&'),
        }
    }
}

impl Serializer for Urlencoder {
    type Output = String;

    fn serialize_parameter<V>(&mut self, k: &str, v: V)
    where
        V: std::fmt::Display,
    {
        self.append_delim();
        write!(self.data, "{}={}", k, PercentEncode(&v)).unwrap();
    }

    fn serialize_parameter_encoded<V>(&mut self, k: &str, v: V)
    where
        V: std::fmt::Display,
    {
        self.append_delim();
        write!(self.data, "{}={}", k, v).unwrap();
    }

    super::skip_serialize_oauth_parameters!();

    fn end(self) -> Self::Output {
        self.data
    }
}