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

use core::fmt::Write;

use crate::util::PercentEncode;

use super::Serializer;

cfg_type_param_hack! {
    /// A `Serializer` that produces a URI query or an `x-www-form-urlencoded` string from a
    /// request.
    #[derive(Clone, Debug)]
    pub struct Urlencoder<
        #[cfg(feature = "alloc")] W = alloc::string::String,
        #[cfg(not(feature = "alloc"))] W,
    > {
        data: W,
        next_append: Append,
    }
}

#[derive(Clone, Debug)]
enum Append {
    None,
    Question,
    Ampersand,
}

doc_auto_cfg! {
    #[cfg(feature = "alloc")]
    impl Urlencoder {
        /// Creates a `Urlencoder` that produces an `x-www-form-urlencoded` string.
        pub fn form() -> Self {
            Urlencoder {
                data: alloc::string::String::new(),
                next_append: Append::None,
            }
        }
    }
}

impl<W> Urlencoder<W>
where
    W: Write,
{
    /// Same with `form` but writes the resulting form string into `buf`.
    pub fn form_with_buf(buf: W) -> Self {
        Urlencoder {
            data: buf,
            next_append: Append::None,
        }
    }

    /// Creates a `Urlencoder` that appends a query part to the given URI.
    pub fn query(uri: W) -> 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.write_char('?').unwrap();
                self.next_append = Append::Ampersand;
            }
            Append::Ampersand => self.data.write_char('&').unwrap(),
        }
    }
}

impl<W: Write> Serializer for Urlencoder<W> {
    type Output = W;

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

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

    super::skip_serialize_oauth_parameters!();

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