summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorSam Scott <sam.scott89@gmail.com>2017-11-09 16:52:42 +0000
committerSam Scott <sam.scott89@gmail.com>2017-11-09 16:52:42 +0000
commit9a453f02364915bfc45e879267cbd0f710e746f1 (patch)
tree9cec3e41e25411967b40578c94f80c19e6e0c0e5 /src
parentf8a8887318d0595a028f0a4a62001b229ebdf942 (diff)
Add generic serialize `to_writer` method.
Diffstat (limited to 'src')
-rw-r--r--src/lib.rs2
-rw-r--r--src/ser.rs36
2 files changed, 37 insertions, 1 deletions
diff --git a/src/lib.rs b/src/lib.rs
index e5ee7e2..d55f0b4 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -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};
diff --git a/src/ser.rs b/src/ser.rs
index a78d6be..4206e60 100644
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -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.