From aa4782fcb6806a4ccc1a15dc9a58f58249c52178 Mon Sep 17 00:00:00 2001 From: Jake Shadle Date: Thu, 11 Jul 2019 17:55:53 +0200 Subject: [PATCH] Pass input by ref Also adds a more "traditional" serde test that is an example of the use case that spurred this change. --- src/ser/mod.rs | 5 ++++- tests/test_serialize.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/ser/mod.rs b/src/ser/mod.rs index 633f1fa..5f65ccd 100644 --- a/src/ser/mod.rs +++ b/src/ser/mod.rs @@ -27,7 +27,10 @@ use url::form_urlencoded::Target as UrlEncodedTarget; /// serde_urlencoded::to_string(meal), /// Ok("bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter".to_owned())); /// ``` -pub fn to_string(input: T) -> Result { +pub fn to_string(input: &T) -> Result +where + T: ser::Serialize + ?Sized, +{ let mut urlencoder = UrlEncodedSerializer::new("".to_owned()); input.serialize(Serializer::new(&mut urlencoder))?; Ok(urlencoder.finish()) diff --git a/tests/test_serialize.rs b/tests/test_serialize.rs index 6f99cba..4661f92 100644 --- a/tests/test_serialize.rs +++ b/tests/test_serialize.rs @@ -73,3 +73,32 @@ fn serialize_unit_enum() { Ok("one=A&two=B&three=C".to_owned()) ); } + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +enum OtherComplex<'a> { + SomeString(&'a str), +} + +#[derive(Serialize)] +struct Complex<'a> { + a: u32, + #[serde(skip_serializing_if = "Option::is_none")] + b: Option<&'a str>, + #[serde(flatten)] + c: OtherComplex<'a>, +} + +#[test] +fn serialize_complex() { + let complex = Complex { + a: 23, + b: None, + c: OtherComplex::SomeString("a string"), + }; + + assert_eq!( + serde_urlencoded::to_string(&complex), + Ok("a=23&someString=a+string".to_owned()) + ); +}