Skip to content

Commit 193bdf4

Browse files
authored
Add push_to_string for appending data to an already existing buffer
1 parent 79fa323 commit 193bdf4

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

src/ser.rs

+21-2
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,28 @@ pub use self::error::Error;
2424
/// );
2525
/// ```
2626
pub fn to_string<T: ser::Serialize>(input: T) -> Result<String, Error> {
27-
let mut urlencoder = UrlEncodedSerializer::new("".to_owned());
27+
let mut target = String::new();
28+
push_to_string(&mut target, input)?;
29+
Ok(target)
30+
}
31+
32+
/// Serializes a value into the provided `application/x-www-form-urlencoded` `String` buffer.
33+
///
34+
/// ```
35+
/// let meal = &[("bread", "baguette"), ("cheese", "comté"), ("meat", "ham"), ("fat", "butter")];
36+
///
37+
/// let mut target = "/cook?".to_owned();
38+
///
39+
/// serde_html_form::ser::push_to_string(&mut target, meal).unwrap();
40+
///
41+
/// assert_eq!(target, "/cook?bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter");
42+
/// ```
43+
pub fn push_to_string<T: ser::Serialize>(target: &mut String, input: T) -> Result<(), Error> {
44+
let start_position = target.len();
45+
let mut urlencoder = UrlEncodedSerializer::for_suffix(target, start_position);
2846
input.serialize(Serializer::new(&mut urlencoder))?;
29-
Ok(urlencoder.finish())
47+
urlencoder.finish();
48+
Ok(())
3049
}
3150

3251
/// A serializer for the `application/x-www-form-urlencoded` format.

0 commit comments

Comments
 (0)