From 967549d85996443bee850c492e23cf40fb889ec4 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 11 Sep 2016 18:49:29 +0200 Subject: Add convenience functions (fixes #2) --- src/de.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'src/de.rs') diff --git a/src/de.rs b/src/de.rs index 8925f52..695547f 100644 --- a/src/de.rs +++ b/src/de.rs @@ -4,9 +4,48 @@ use serde::de; use serde::de::value::MapDeserializer; use std::borrow::Cow; use url::form_urlencoded::Parse as UrlEncodedParse; +use url::form_urlencoded::parse; pub use serde::de::value::Error; +/// Deserializes a `application/x-wwww-url-encoded` value from a `&[u8]`. +/// +/// ``` +/// let meal = vec![ +/// ("bread".to_owned(), "baguette".to_owned()), +/// ("cheese".to_owned(), "comté".to_owned()), +/// ("meat".to_owned(), "ham".to_owned()), +/// ("fat".to_owned(), "butter".to_owned()), +/// ]; +/// +/// assert_eq!( +/// serde_urlencoded::from_bytes::>( +/// b"bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter"), +/// Ok(meal)); +/// ``` +pub fn from_bytes(input: &[u8]) -> Result { + T::deserialize(&mut Deserializer::new(parse(input))) +} + +/// Deserializes a `application/x-wwww-url-encoded` value from a `&str`. +/// +/// ``` +/// let meal = vec![ +/// ("bread".to_owned(), "baguette".to_owned()), +/// ("cheese".to_owned(), "comté".to_owned()), +/// ("meat".to_owned(), "ham".to_owned()), +/// ("fat".to_owned(), "butter".to_owned()), +/// ]; +/// +/// assert_eq!( +/// serde_urlencoded::from_str::>( +/// "bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter"), +/// Ok(meal)); +/// ``` +pub fn from_str(input: &str) -> Result { + from_bytes(input.as_bytes()) +} + /// A deserializer for the `application/x-www-form-urlencoded` format. /// /// * Supported top-level outputs are structs, maps and sequences of pairs, -- cgit v1.2.3