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
//! # Serde URL Params
//!
//! This module provides a simple and flexible way for serializing data
//! structures into URL parameters strings.
//!
//! A data structure can be converted to such string by
//! [`serde_url_params::to_string`][to_string] function. There is also
//! [`serde_url_params::to_vec`][to_vec] which serializes to a `Vec<u8>` and
//! [`serde_url_params::to_writer`][to_writer] which serializes to any
//! `io::Write` such as a File or a TCP stream.
//!
//! ```rust
//! extern crate serde;
//! extern crate serde_url_params;
//!
//! #[macro_use]
//! extern crate serde_derive;
//!
//! use serde_url_params::Error;
//!
//! #[derive(Serialize)]
//! enum Filter {
//!     Horror,
//!     Comedy,
//!     Thriller,
//!     Drama,
//! }
//!
//! #[derive(Serialize)]
//! struct Options {
//!     year: u16,
//!     actors: Vec<String>,
//! }
//!
//! #[derive(Serialize)]
//! struct SearchRequest {
//!     film: String,
//!     per_page: Option<usize>,
//!     next: Option<usize>,
//!     filter: Vec<Filter>,
//!     #[serde(flatten)]
//!     options: Options,
//! }
//!
//! fn print_url_params() -> Result<(), Error> {
//!     // Some data structure.
//!     let request = SearchRequest {
//!         film: String::from("Fight Club"),
//!         per_page: Some(20),
//!         next: None,
//!         filter: vec![Filter::Thriller, Filter::Drama],
//!         options: Options {
//!             year: 1999,
//!             actors: vec!["Edward Norton".into()],
//!         },
//!     };
//!
//!     // Serialize it to a URL parameters string.
//!     let p = serde_url_params::to_string(&request)?;
//!
//!     assert_eq!(
//!         p,
//!         "film=Fight+Club&per_page=20&filter=Thriller&filter=Drama&year=1999&actors=Edward+Norton"
//!     );
//!
//!     Ok(())
//! }
//!
//! fn main() {
//!     print_url_params().unwrap();
//! }
//! ```
//!
//! Almost any type that implements Serde's `Serialize` trait can be serialized
//! this way. This includes the built-in Rust standard library types `Vec<T>`
//! as you can see in the above example, as well as structs or enums annotated
//! with `#[derive(Serialize)]`. However, there are exceptions, for which it is
//! not obvious how to serialize them into flat parameters list:
//!
//! * any simple top level value, since it does not have a parameter key, and
//! * any nested struct, since it is not obvious how to flatten it,
//! * any map, which is not flattened (i.e. annotated with `#[serde(flatten)]`).
//!
//! Further, any string is automatically URL encoded (or more precisely,
//! percentage encoded). Elements in `Vec`s are serialized as repeated
//! `key=value` pairs, where key is the field holding the vector. Newtype
//! variants and variant structs are flattened by omitting the name of the
//! variant resp. struct.
//!
//! [to_string]: ser/fn.to_string.html
//! [to_vec]: ser/fn.to_vec.html
//! [to_writer]: ser/fn.to_writer.html

#![deny(missing_docs)]

extern crate serde;
#[cfg(test)]
#[macro_use]
extern crate serde_derive;
extern crate url;

#[doc(inline)]
pub use self::error::{Error, Result};
#[doc(inline)]
pub use self::ser::{to_string, to_vec, to_writer, Serializer};

pub mod error;
pub mod ser;

#[cfg(test)]
mod tests {
    use super::to_string;

    #[derive(Debug, Serialize)]
    enum Selection {
        A,
        B,
    }

    #[derive(Debug, Serialize)]
    struct Request {
        id: String,
        filter: Vec<String>,
        option: Option<String>,
        optional_filter: Option<Vec<String>>,
        select: Selection,
        select2: Vec<Selection>,
        num: Option<usize>,
        results: Vec<::std::result::Result<&'static str, &'static str>>,
    }

    #[test]
    fn test() {
        let request = Request {
            id: String::from("some_id"),
            filter: vec![String::from("filter1"), String::from("filter2")],
            option: None,
            optional_filter: Some(vec![String::from("filter3")]),
            select: Selection::A,
            select2: vec![Selection::A, Selection::B],
            num: Some(42),
            results: vec![Ok("pass"), Err("fail")],
        };
        let get_params = to_string(&request);
        assert!(get_params.is_ok());
        assert_eq!(
            get_params.unwrap(),
            "id=some_id&filter=filter1&filter=filter2&optional_filter=filter3&select=A&select2=A&select2=B&num=42&results=pass&results=fail"
        );
    }

    #[test]
    fn test_newtype_struct() {
        #[derive(Debug, Serialize)]
        struct NewType(usize);
        #[derive(Debug, Serialize)]
        struct Params {
            field: NewType,
        }
        let params = Params { field: NewType(42) };
        let url_params = to_string(&params);
        assert!(url_params.is_ok());
        assert_eq!(url_params.unwrap(), "field=42");
    }

    #[test]
    fn test_tuple() {
        #[derive(Debug, Serialize)]
        struct Params {
            field: (usize, &'static str, f32),
        }
        let params = Params {
            field: (42, "hello", 3.14),
        };
        let url_params = to_string(&params);
        assert!(url_params.is_ok());
        assert_eq!(url_params.unwrap(), "field=42&field=hello&field=3.14");
    }

    #[test]
    fn test_tuple_struct() {
        #[derive(Debug, Serialize)]
        struct TupleStruct(usize, &'static str, f32);
        #[derive(Debug, Serialize)]
        struct Params {
            field: TupleStruct,
        }
        let params = Params {
            field: TupleStruct(42, "hello", 3.14),
        };
        let url_params = to_string(&params);
        assert!(url_params.is_ok());
        assert_eq!(url_params.unwrap(), "field=42&field=hello&field=3.14");
    }

    #[test]
    fn test_struct() {
        #[derive(Debug, Serialize)]
        struct A {
            username: String,
        }
        #[derive(Debug, Serialize)]
        struct Params {
            field: A,
        }
        // top level struct is supported
        {
            let params = A {
                username: String::from("boxdot"),
            };
            let url_params = to_string(&params);
            assert!(url_params.is_ok());
            assert_eq!(url_params.unwrap(), "username=boxdot");
        }
        // nested struct is not supported
        {
            let params = Params {
                field: A {
                    username: String::from("boxdot"),
                },
            };
            let url_params = to_string(&params);
            assert!(url_params.is_err());
        }
    }

    #[test]
    fn test_struct_variant() {
        #[derive(Debug, Serialize)]
        enum StructVariant {
            A { username: String },
        }
        #[derive(Debug, Serialize)]
        struct Params {
            field: StructVariant,
        }
        // top level struct variant is supported
        {
            let params = StructVariant::A {
                username: String::from("boxdot"),
            };
            let url_params = to_string(&params);
            assert!(url_params.is_ok());
            assert_eq!(url_params.unwrap(), "username=boxdot");
        }
        // nested struct variant is not supported
        {
            let params = Params {
                field: StructVariant::A {
                    username: String::from("boxdot"),
                },
            };
            let url_params = to_string(&params);
            assert!(url_params.is_err());
        }
    }

    #[test]
    fn test_urlencoded() {
        #[derive(Debug, Serialize)]
        struct Params {
            field: String,
        }
        let params = Params {
            field: String::from("{some=weird&param}"),
        };
        let url_params = to_string(&params);
        assert!(url_params.is_ok());
        assert_eq!(url_params.unwrap(), "field=%7Bsome%3Dweird%26param%7D");
    }

    #[test]
    fn test_flattened_struct() {
        #[derive(Serialize, Debug)]
        pub struct Complex {
            real: f64,
            imag: f64,
        }

        #[derive(Serialize, Debug)]
        pub struct Params {
            x: u64,
            #[serde(flatten)]
            z: Option<Complex>,
        }

        let params = Params {
            x: 1,
            z: Some(Complex {
                real: 0.0,
                imag: 1.0,
            }),
        };
        let url_params = to_string(&params);
        assert_eq!(
            url_params.expect("failed serialization"),
            "x=1&real=0&imag=1"
        );
    }

    #[test]
    fn test_seq_of_struct() {
        #[derive(Serialize, Debug)]
        pub struct Complex {
            real: f64,
            imag: f64,
        }

        #[derive(Serialize, Debug)]
        #[serde(transparent)]
        pub struct Params {
            seq: Vec<Complex>,
        }

        let params = Params {
            seq: vec![
                Complex {
                    real: 0.0,
                    imag: 1.0,
                },
                Complex {
                    real: 1.0,
                    imag: 0.0,
                },
            ],
        };
        let url_params = to_string(&params);
        assert_eq!(
            url_params.expect("failed serialization"),
            "real=0&imag=1&real=1&imag=0"
        );
    }
}