From a9a05350a9421f928d94efba684b6318767b3eb7 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 26 Feb 2017 15:02:15 +0100 Subject: [PATCH] Introduce Serializer::collect_str (fixes #786) The default implementation collects the Display value into a String and then passes that to Serializer::serialize_str when the std or collections features are enabled, otherwise it unconditionally returns an error. --- serde/src/ser/mod.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs index 38f9ec7b..f69ab635 100644 --- a/serde/src/ser/mod.rs +++ b/serde/src/ser/mod.rs @@ -98,7 +98,11 @@ use std::error; #[cfg(not(feature = "std"))] use error; +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::string::String; use core::fmt::Display; +#[cfg(any(feature = "std", feature = "collections"))] +use core::fmt::Write; use core::iter::IntoIterator; mod impls; @@ -616,6 +620,29 @@ pub trait Serializer: Sized { } serializer.end() } + + /// Collect a `Display` value as a string. + /// + /// The default implementation serializes the given value as a string with + /// `ToString::to_string`. + #[cfg(any(feature = "std", feature = "collections"))] + fn collect_str(self, value: &T) -> Result + where T: Display, + { + let mut string = String::new(); + write!(string, "{}", value).unwrap(); + self.serialize_str(&string) + } + + /// Collect a `Display` value as a string. + /// + /// The default implementation returns an error unconditionally. + #[cfg(not(any(feature = "std", feature = "collections")))] + fn collect_str(self, _value: &T) -> Result + where T: Display, + { + Err(Error::custom("Default impl of collect_str errors out for no_std builds")) + } } /// Returned from `Serializer::serialize_seq` and