Skip to content

Commit

Permalink
Introduce Serializer::collect_str (fixes #786)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
nox committed Feb 28, 2017
1 parent abc081c commit a9a0535
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions serde/src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
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<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
where T: Display,
{
Err(Error::custom("Default impl of collect_str errors out for no_std builds"))
}
}

/// Returned from `Serializer::serialize_seq` and
Expand Down

0 comments on commit a9a0535

Please sign in to comment.