From 2184fef82f0d1c5ce3a953f3c96ce4b6c2568c43 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sun, 5 Mar 2017 16:43:31 -0800 Subject: [PATCH] Add format_args example to collect_str --- serde/src/ser/mod.rs | 48 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs index ec3a72c6..f91db459 100644 --- a/serde/src/ser/mod.rs +++ b/serde/src/ser/mod.rs @@ -621,10 +621,29 @@ pub trait Serializer: Sized { serializer.end() } - /// Collect a `Display` value as a string. + /// Serialize a string produced by an implementation of `Display`. /// - /// The default implementation serializes the given value as a string with - /// `ToString::to_string`. + /// The default implementation builds a heap-allocated `String` and + /// delegates to `serialize_str`. Serializers are encouraged to provide a + /// more efficient implementation if possible. + /// + /// ```rust + /// # use serde::{Serialize, Serializer}; + /// # struct DateTime; + /// # impl DateTime { + /// # fn naive_local(&self) -> () { () } + /// # fn offset(&self) -> () { () } + /// # } + /// impl Serialize for DateTime { + /// fn serialize(&self, serializer: S) -> Result + /// where S: Serializer + /// { + /// serializer.collect_str(&format_args!("{:?}{:?}", + /// self.naive_local(), + /// self.offset())) + /// } + /// } + /// ``` #[cfg(any(feature = "std", feature = "collections"))] fn collect_str(self, value: &T) -> Result where T: Display, @@ -634,9 +653,28 @@ pub trait Serializer: Sized { self.serialize_str(&string) } - /// Collect a `Display` value as a string. + /// Serialize a string produced by an implementation of `Display`. /// - /// The default implementation returns an error unconditionally. + /// The default implementation returns an error unconditionally when + /// compiled with `no_std`. + /// + /// ```rust + /// # use serde::{Serialize, Serializer}; + /// # struct DateTime; + /// # impl DateTime { + /// # fn naive_local(&self) -> () { () } + /// # fn offset(&self) -> () { () } + /// # } + /// impl Serialize for DateTime { + /// fn serialize(&self, serializer: S) -> Result + /// where S: Serializer + /// { + /// serializer.collect_str(&format_args!("{:?}{:?}", + /// self.naive_local(), + /// self.offset())) + /// } + /// } + /// ``` #[cfg(not(any(feature = "std", feature = "collections")))] fn collect_str(self, value: &T) -> Result where T: Display,