1 | //! Serialization support for the `application/x-www-form-urlencoded` format. |
2 | |
3 | mod key; |
4 | mod pair; |
5 | mod part; |
6 | mod value; |
7 | |
8 | use form_urlencoded::Serializer as UrlEncodedSerializer; |
9 | use form_urlencoded::Target as UrlEncodedTarget; |
10 | use serde::ser; |
11 | use std::borrow::Cow; |
12 | use std::error; |
13 | use std::fmt; |
14 | use std::str; |
15 | |
16 | /// Serializes a value into a `application/x-www-form-urlencoded` `String` buffer. |
17 | /// |
18 | /// ``` |
19 | /// let meal = &[ |
20 | /// ("bread" , "baguette" ), |
21 | /// ("cheese" , "comté" ), |
22 | /// ("meat" , "ham" ), |
23 | /// ("fat" , "butter" ), |
24 | /// ]; |
25 | /// |
26 | /// assert_eq!( |
27 | /// serde_urlencoded::to_string(meal), |
28 | /// Ok("bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter" .to_owned())); |
29 | /// ``` |
30 | pub fn to_string<T: ser::Serialize>(input: T) -> Result<String, Error> { |
31 | let mut urlencoder: Serializer<'_, String> = UrlEncodedSerializer::new(target:"" .to_owned()); |
32 | input.serialize(Serializer::new(&mut urlencoder))?; |
33 | Ok(urlencoder.finish()) |
34 | } |
35 | |
36 | /// A serializer for the `application/x-www-form-urlencoded` format. |
37 | /// |
38 | /// * Supported top-level inputs are structs, maps and sequences of pairs, |
39 | /// with or without a given length. |
40 | /// |
41 | /// * Supported keys and values are integers, bytes (if convertible to strings), |
42 | /// unit structs and unit variants. |
43 | /// |
44 | /// * Newtype structs defer to their inner values. |
45 | pub struct Serializer<'input, 'output, Target: UrlEncodedTarget> { |
46 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, |
47 | } |
48 | |
49 | impl<'input, 'output, Target: 'output + UrlEncodedTarget> |
50 | Serializer<'input, 'output, Target> |
51 | { |
52 | /// Returns a new `Serializer`. |
53 | pub fn new( |
54 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, |
55 | ) -> Self { |
56 | Serializer { urlencoder } |
57 | } |
58 | } |
59 | |
60 | /// Errors returned during serializing to `application/x-www-form-urlencoded`. |
61 | #[derive (Clone, Debug, PartialEq, Eq)] |
62 | pub enum Error { |
63 | Custom(Cow<'static, str>), |
64 | Utf8(str::Utf8Error), |
65 | } |
66 | |
67 | impl fmt::Display for Error { |
68 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
69 | match *self { |
70 | Error::Custom(ref msg: &Cow<'_, str>) => msg.fmt(f), |
71 | Error::Utf8(ref err: &Utf8Error) => write!(f, "invalid UTF-8: {}" , err), |
72 | } |
73 | } |
74 | } |
75 | |
76 | impl error::Error for Error { |
77 | fn description(&self) -> &str { |
78 | match *self { |
79 | Error::Custom(ref msg: &Cow<'_, str>) => msg, |
80 | Error::Utf8(ref err: &Utf8Error) => error::Error::description(self:err), |
81 | } |
82 | } |
83 | |
84 | /// The lower-level cause of this error, in the case of a `Utf8` error. |
85 | fn cause(&self) -> Option<&dyn error::Error> { |
86 | match *self { |
87 | Error::Custom(_) => None, |
88 | Error::Utf8(ref err: &Utf8Error) => Some(err), |
89 | } |
90 | } |
91 | |
92 | /// The lower-level source of this error, in the case of a `Utf8` error. |
93 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { |
94 | match *self { |
95 | Error::Custom(_) => None, |
96 | Error::Utf8(ref err: &Utf8Error) => Some(err), |
97 | } |
98 | } |
99 | } |
100 | |
101 | impl ser::Error for Error { |
102 | fn custom<T: fmt::Display>(msg: T) -> Self { |
103 | Error::Custom(format!(" {}" , msg).into()) |
104 | } |
105 | } |
106 | |
107 | /// Sequence serializer. |
108 | pub struct SeqSerializer<'input, 'output, Target: UrlEncodedTarget> { |
109 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, |
110 | } |
111 | |
112 | /// Tuple serializer. |
113 | /// |
114 | /// Mostly used for arrays. |
115 | pub struct TupleSerializer<'input, 'output, Target: UrlEncodedTarget> { |
116 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, |
117 | } |
118 | |
119 | /// Tuple struct serializer. |
120 | /// |
121 | /// Never instantiated, tuple structs are not supported. |
122 | pub struct TupleStructSerializer<'input, 'output, T: UrlEncodedTarget> { |
123 | inner: ser::Impossible<&'output mut UrlEncodedSerializer<'input, T>, Error>, |
124 | } |
125 | |
126 | /// Tuple variant serializer. |
127 | /// |
128 | /// Never instantiated, tuple variants are not supported. |
129 | pub struct TupleVariantSerializer<'input, 'output, T: UrlEncodedTarget> { |
130 | inner: ser::Impossible<&'output mut UrlEncodedSerializer<'input, T>, Error>, |
131 | } |
132 | |
133 | /// Map serializer. |
134 | pub struct MapSerializer<'input, 'output, Target: UrlEncodedTarget> { |
135 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, |
136 | key: Option<Cow<'static, str>>, |
137 | } |
138 | |
139 | /// Struct serializer. |
140 | pub struct StructSerializer<'input, 'output, Target: UrlEncodedTarget> { |
141 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, |
142 | } |
143 | |
144 | /// Struct variant serializer. |
145 | /// |
146 | /// Never instantiated, struct variants are not supported. |
147 | pub struct StructVariantSerializer<'input, 'output, T: UrlEncodedTarget> { |
148 | inner: ser::Impossible<&'output mut UrlEncodedSerializer<'input, T>, Error>, |
149 | } |
150 | |
151 | impl<'input, 'output, Target> ser::Serializer |
152 | for Serializer<'input, 'output, Target> |
153 | where |
154 | Target: 'output + UrlEncodedTarget, |
155 | { |
156 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; |
157 | type Error = Error; |
158 | type SerializeSeq = SeqSerializer<'input, 'output, Target>; |
159 | type SerializeTuple = TupleSerializer<'input, 'output, Target>; |
160 | type SerializeTupleStruct = TupleStructSerializer<'input, 'output, Target>; |
161 | type SerializeTupleVariant = |
162 | TupleVariantSerializer<'input, 'output, Target>; |
163 | type SerializeMap = MapSerializer<'input, 'output, Target>; |
164 | type SerializeStruct = StructSerializer<'input, 'output, Target>; |
165 | type SerializeStructVariant = |
166 | StructVariantSerializer<'input, 'output, Target>; |
167 | |
168 | /// Returns an error. |
169 | fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Error> { |
170 | Err(Error::top_level()) |
171 | } |
172 | |
173 | /// Returns an error. |
174 | fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Error> { |
175 | Err(Error::top_level()) |
176 | } |
177 | |
178 | /// Returns an error. |
179 | fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Error> { |
180 | Err(Error::top_level()) |
181 | } |
182 | |
183 | /// Returns an error. |
184 | fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Error> { |
185 | Err(Error::top_level()) |
186 | } |
187 | |
188 | /// Returns an error. |
189 | fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Error> { |
190 | Err(Error::top_level()) |
191 | } |
192 | |
193 | /// Returns an error. |
194 | fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Error> { |
195 | Err(Error::top_level()) |
196 | } |
197 | |
198 | /// Returns an error. |
199 | fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Error> { |
200 | Err(Error::top_level()) |
201 | } |
202 | |
203 | /// Returns an error. |
204 | fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Error> { |
205 | Err(Error::top_level()) |
206 | } |
207 | |
208 | /// Returns an error. |
209 | fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Error> { |
210 | Err(Error::top_level()) |
211 | } |
212 | |
213 | /// Returns an error. |
214 | fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Error> { |
215 | Err(Error::top_level()) |
216 | } |
217 | |
218 | /// Returns an error. |
219 | fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Error> { |
220 | Err(Error::top_level()) |
221 | } |
222 | |
223 | /// Returns an error. |
224 | fn serialize_char(self, _v: char) -> Result<Self::Ok, Error> { |
225 | Err(Error::top_level()) |
226 | } |
227 | |
228 | /// Returns an error. |
229 | fn serialize_str(self, _value: &str) -> Result<Self::Ok, Error> { |
230 | Err(Error::top_level()) |
231 | } |
232 | |
233 | /// Returns an error. |
234 | fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok, Error> { |
235 | Err(Error::top_level()) |
236 | } |
237 | |
238 | /// Returns `Ok`. |
239 | fn serialize_unit(self) -> Result<Self::Ok, Error> { |
240 | Ok(self.urlencoder) |
241 | } |
242 | |
243 | /// Returns `Ok`. |
244 | fn serialize_unit_struct( |
245 | self, |
246 | _name: &'static str, |
247 | ) -> Result<Self::Ok, Error> { |
248 | Ok(self.urlencoder) |
249 | } |
250 | |
251 | /// Returns an error. |
252 | fn serialize_unit_variant( |
253 | self, |
254 | _name: &'static str, |
255 | _variant_index: u32, |
256 | _variant: &'static str, |
257 | ) -> Result<Self::Ok, Error> { |
258 | Err(Error::top_level()) |
259 | } |
260 | |
261 | /// Serializes the inner value, ignoring the newtype name. |
262 | fn serialize_newtype_struct<T: ?Sized + ser::Serialize>( |
263 | self, |
264 | _name: &'static str, |
265 | value: &T, |
266 | ) -> Result<Self::Ok, Error> { |
267 | value.serialize(self) |
268 | } |
269 | |
270 | /// Returns an error. |
271 | fn serialize_newtype_variant<T: ?Sized + ser::Serialize>( |
272 | self, |
273 | _name: &'static str, |
274 | _variant_index: u32, |
275 | _variant: &'static str, |
276 | _value: &T, |
277 | ) -> Result<Self::Ok, Error> { |
278 | Err(Error::top_level()) |
279 | } |
280 | |
281 | /// Returns `Ok`. |
282 | fn serialize_none(self) -> Result<Self::Ok, Error> { |
283 | Ok(self.urlencoder) |
284 | } |
285 | |
286 | /// Serializes the given value. |
287 | fn serialize_some<T: ?Sized + ser::Serialize>( |
288 | self, |
289 | value: &T, |
290 | ) -> Result<Self::Ok, Error> { |
291 | value.serialize(self) |
292 | } |
293 | |
294 | /// Serialize a sequence, given length (if any) is ignored. |
295 | fn serialize_seq( |
296 | self, |
297 | _len: Option<usize>, |
298 | ) -> Result<Self::SerializeSeq, Error> { |
299 | Ok(SeqSerializer { |
300 | urlencoder: self.urlencoder, |
301 | }) |
302 | } |
303 | |
304 | /// Returns an error. |
305 | fn serialize_tuple( |
306 | self, |
307 | _len: usize, |
308 | ) -> Result<Self::SerializeTuple, Error> { |
309 | Ok(TupleSerializer { |
310 | urlencoder: self.urlencoder, |
311 | }) |
312 | } |
313 | |
314 | /// Returns an error. |
315 | fn serialize_tuple_struct( |
316 | self, |
317 | _name: &'static str, |
318 | _len: usize, |
319 | ) -> Result<Self::SerializeTupleStruct, Error> { |
320 | Err(Error::top_level()) |
321 | } |
322 | |
323 | /// Returns an error. |
324 | fn serialize_tuple_variant( |
325 | self, |
326 | _name: &'static str, |
327 | _variant_index: u32, |
328 | _variant: &'static str, |
329 | _len: usize, |
330 | ) -> Result<Self::SerializeTupleVariant, Error> { |
331 | Err(Error::top_level()) |
332 | } |
333 | |
334 | /// Serializes a map, given length is ignored. |
335 | fn serialize_map( |
336 | self, |
337 | _len: Option<usize>, |
338 | ) -> Result<Self::SerializeMap, Error> { |
339 | Ok(MapSerializer { |
340 | urlencoder: self.urlencoder, |
341 | key: None, |
342 | }) |
343 | } |
344 | |
345 | /// Serializes a struct, given length is ignored. |
346 | fn serialize_struct( |
347 | self, |
348 | _name: &'static str, |
349 | _len: usize, |
350 | ) -> Result<Self::SerializeStruct, Error> { |
351 | Ok(StructSerializer { |
352 | urlencoder: self.urlencoder, |
353 | }) |
354 | } |
355 | |
356 | /// Returns an error. |
357 | fn serialize_struct_variant( |
358 | self, |
359 | _name: &'static str, |
360 | _variant_index: u32, |
361 | _variant: &'static str, |
362 | _len: usize, |
363 | ) -> Result<Self::SerializeStructVariant, Error> { |
364 | Err(Error::top_level()) |
365 | } |
366 | } |
367 | |
368 | impl<'input, 'output, Target> ser::SerializeSeq |
369 | for SeqSerializer<'input, 'output, Target> |
370 | where |
371 | Target: 'output + UrlEncodedTarget, |
372 | { |
373 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; |
374 | type Error = Error; |
375 | |
376 | fn serialize_element<T: ?Sized + ser::Serialize>( |
377 | &mut self, |
378 | value: &T, |
379 | ) -> Result<(), Error> { |
380 | value.serialize(serializer:pair::PairSerializer::new(self.urlencoder)) |
381 | } |
382 | |
383 | fn end(self) -> Result<Self::Ok, Error> { |
384 | Ok(self.urlencoder) |
385 | } |
386 | } |
387 | |
388 | impl<'input, 'output, Target> ser::SerializeTuple |
389 | for TupleSerializer<'input, 'output, Target> |
390 | where |
391 | Target: 'output + UrlEncodedTarget, |
392 | { |
393 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; |
394 | type Error = Error; |
395 | |
396 | fn serialize_element<T: ?Sized + ser::Serialize>( |
397 | &mut self, |
398 | value: &T, |
399 | ) -> Result<(), Error> { |
400 | value.serialize(serializer:pair::PairSerializer::new(self.urlencoder)) |
401 | } |
402 | |
403 | fn end(self) -> Result<Self::Ok, Error> { |
404 | Ok(self.urlencoder) |
405 | } |
406 | } |
407 | |
408 | impl<'input, 'output, Target> ser::SerializeTupleStruct |
409 | for TupleStructSerializer<'input, 'output, Target> |
410 | where |
411 | Target: 'output + UrlEncodedTarget, |
412 | { |
413 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; |
414 | type Error = Error; |
415 | |
416 | fn serialize_field<T: ?Sized + ser::Serialize>( |
417 | &mut self, |
418 | value: &T, |
419 | ) -> Result<(), Error> { |
420 | self.inner.serialize_field(value) |
421 | } |
422 | |
423 | fn end(self) -> Result<Self::Ok, Error> { |
424 | self.inner.end() |
425 | } |
426 | } |
427 | |
428 | impl<'input, 'output, Target> ser::SerializeTupleVariant |
429 | for TupleVariantSerializer<'input, 'output, Target> |
430 | where |
431 | Target: 'output + UrlEncodedTarget, |
432 | { |
433 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; |
434 | type Error = Error; |
435 | |
436 | fn serialize_field<T: ?Sized + ser::Serialize>( |
437 | &mut self, |
438 | value: &T, |
439 | ) -> Result<(), Error> { |
440 | self.inner.serialize_field(value) |
441 | } |
442 | |
443 | fn end(self) -> Result<Self::Ok, Error> { |
444 | self.inner.end() |
445 | } |
446 | } |
447 | |
448 | impl<'input, 'output, Target> ser::SerializeMap |
449 | for MapSerializer<'input, 'output, Target> |
450 | where |
451 | Target: 'output + UrlEncodedTarget, |
452 | { |
453 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; |
454 | type Error = Error; |
455 | |
456 | fn serialize_entry< |
457 | K: ?Sized + ser::Serialize, |
458 | V: ?Sized + ser::Serialize, |
459 | >( |
460 | &mut self, |
461 | key: &K, |
462 | value: &V, |
463 | ) -> Result<(), Error> { |
464 | let key_sink = key::KeySink::new(|key| { |
465 | let value_sink = value::ValueSink::new(self.urlencoder, &key); |
466 | value.serialize(part::PartSerializer::new(value_sink))?; |
467 | self.key = None; |
468 | Ok(()) |
469 | }); |
470 | let entry_serializer = part::PartSerializer::new(key_sink); |
471 | key.serialize(entry_serializer) |
472 | } |
473 | |
474 | fn serialize_key<T: ?Sized + ser::Serialize>( |
475 | &mut self, |
476 | key: &T, |
477 | ) -> Result<(), Error> { |
478 | let key_sink = key::KeySink::new(|key| Ok(key.into())); |
479 | let key_serializer = part::PartSerializer::new(key_sink); |
480 | self.key = Some(key.serialize(key_serializer)?); |
481 | Ok(()) |
482 | } |
483 | |
484 | fn serialize_value<T: ?Sized + ser::Serialize>( |
485 | &mut self, |
486 | value: &T, |
487 | ) -> Result<(), Error> { |
488 | { |
489 | let key = self.key.as_ref().ok_or_else(Error::no_key)?; |
490 | let value_sink = value::ValueSink::new(self.urlencoder, &key); |
491 | value.serialize(part::PartSerializer::new(value_sink))?; |
492 | } |
493 | self.key = None; |
494 | Ok(()) |
495 | } |
496 | |
497 | fn end(self) -> Result<Self::Ok, Error> { |
498 | Ok(self.urlencoder) |
499 | } |
500 | } |
501 | |
502 | impl<'input, 'output, Target> ser::SerializeStruct |
503 | for StructSerializer<'input, 'output, Target> |
504 | where |
505 | Target: 'output + UrlEncodedTarget, |
506 | { |
507 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; |
508 | type Error = Error; |
509 | |
510 | fn serialize_field<T: ?Sized + ser::Serialize>( |
511 | &mut self, |
512 | key: &'static str, |
513 | value: &T, |
514 | ) -> Result<(), Error> { |
515 | let value_sink: ValueSink<'_, '_, '_, Target> = value::ValueSink::new(self.urlencoder, key); |
516 | value.serialize(serializer:part::PartSerializer::new(value_sink)) |
517 | } |
518 | |
519 | fn end(self) -> Result<Self::Ok, Error> { |
520 | Ok(self.urlencoder) |
521 | } |
522 | } |
523 | |
524 | impl<'input, 'output, Target> ser::SerializeStructVariant |
525 | for StructVariantSerializer<'input, 'output, Target> |
526 | where |
527 | Target: 'output + UrlEncodedTarget, |
528 | { |
529 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; |
530 | type Error = Error; |
531 | |
532 | fn serialize_field<T: ?Sized + ser::Serialize>( |
533 | &mut self, |
534 | key: &'static str, |
535 | value: &T, |
536 | ) -> Result<(), Error> { |
537 | self.inner.serialize_field(key, value) |
538 | } |
539 | |
540 | fn end(self) -> Result<Self::Ok, Error> { |
541 | self.inner.end() |
542 | } |
543 | } |
544 | |
545 | impl Error { |
546 | fn top_level() -> Self { |
547 | let msg: &str = "top-level serializer supports only maps and structs" ; |
548 | Error::Custom(msg.into()) |
549 | } |
550 | |
551 | fn no_key() -> Self { |
552 | let msg: &str = "tried to serialize a value before serializing key" ; |
553 | Error::Custom(msg.into()) |
554 | } |
555 | } |
556 | |