@@ -428,13 +428,6 @@ impl<'a> ser::Serializer for &'a mut Serializer {
428428 self . buf . push ( b':' ) ;
429429 self . serialize_struct ( name, len)
430430 }
431-
432- fn collect_str < T : ?Sized > ( self , value : & T ) -> Result < Self :: Ok >
433- where
434- T : fmt:: Display ,
435- {
436- self . serialize_str ( & value. to_string ( ) )
437- }
438431}
439432
440433/// Serializes the given data structure as a string of JSON text
@@ -539,6 +532,7 @@ impl ser::SerializeStructVariant for Unreachable {
539532mod tests {
540533
541534 use super :: to_string;
535+ use serde:: { Serialize , Serializer } ;
542536 use serde_derive:: { Deserialize , Serialize } ;
543537
544538 #[ test]
@@ -869,6 +863,32 @@ mod tests {
869863 assert_eq ! ( to_string( " \u{001f} " ) . unwrap( ) , r#"" \u001F ""# ) ;
870864 }
871865
866+ #[ test]
867+ fn collect_str_can_be_used_in_custom_seralize_impl ( ) {
868+ struct SpecialType {
869+ count : u32 ,
870+ on : bool ,
871+ }
872+
873+ impl Serialize for SpecialType {
874+ // A custom Serialize implementation for SpecialType. SpecialType is giving us the chance to use
875+ // an efficient collect_str implementation that is better than allocating the String and running
876+ // serialize_str on it.
877+ fn serialize < S > ( & self , serializer : S ) -> Result < S :: Ok , S :: Error >
878+ where
879+ S : Serializer ,
880+ {
881+ serializer. collect_str ( & format_args ! ( "{}-{}" , self . count, self . on) )
882+ }
883+ }
884+
885+ let value = SpecialType {
886+ count : 123 ,
887+ on : false ,
888+ } ;
889+ assert_eq ! ( to_string( & value) . unwrap( ) , r#""123-false""# ) ;
890+ }
891+
872892 #[ test]
873893 fn newtype ( ) {
874894 #[ derive( Serialize ) ]
0 commit comments