diff options
author | Sam Scott <sam.scott89@gmail.com> | 2017-11-09 16:52:42 +0000 |
---|---|---|
committer | Sam Scott <sam.scott89@gmail.com> | 2017-11-09 16:52:42 +0000 |
commit | 9a453f02364915bfc45e879267cbd0f710e746f1 (patch) | |
tree | 9cec3e41e25411967b40578c94f80c19e6e0c0e5 /src | |
parent | f8a8887318d0595a028f0a4a62001b229ebdf942 (diff) |
Add generic serialize `to_writer` method.
Diffstat (limited to 'src')
-rw-r--r-- | src/lib.rs | 2 | ||||
-rw-r--r-- | src/ser.rs | 36 |
2 files changed, 37 insertions, 1 deletions
@@ -138,4 +138,4 @@ pub use de::{from_bytes, from_str}; pub use de::Config; pub use error::Error; #[doc(inline)] -pub use ser::{QsSerializer, to_string}; +pub use ser::{QsSerializer, to_string, to_writer}; @@ -63,6 +63,42 @@ pub fn to_string<T: ser::Serialize>(input: &T) -> Result<String> { String::from_utf8(buffer).map_err(Error::from) } +/// Serializes a value into a generic writer object. +/// +/// ``` +/// # #[macro_use] +/// # extern crate serde_derive; +/// # extern crate serde_qs; +/// #[derive(Deserialize, Serialize)] +/// struct Query { +/// name: String, +/// age: u8, +/// occupation: String, +/// } +/// +/// # fn main(){ +/// let q = Query { +/// name: "Alice".to_owned(), +/// age: 24, +/// occupation: "Student".to_owned(), +/// }; +/// +/// let mut buffer = Vec::new(); +/// serde_qs::to_writer(&q, &mut buffer).unwrap(); +/// assert_eq!( +/// String::from_utf8(buffer).unwrap(), +/// "name=Alice&age=24&occupation=Student"); +/// # } +/// ``` +pub fn to_writer<T: ser::Serialize, W: Write>(input: &T, writer: &mut W) -> Result<()> { + let mut first = true; + input.serialize(&mut QsSerializer { + writer: writer, + key: None, + first: &mut first, + }) +} + /// A serializer for the querystring format. /// /// * Supported top-level inputs are structs and maps. |