@@ -428,13 +428,6 @@ impl<'a> ser::Serializer for &'a mut Serializer {
428
428
self . buf . push ( b':' ) ;
429
429
self . serialize_struct ( name, len)
430
430
}
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
- }
438
431
}
439
432
440
433
/// Serializes the given data structure as a string of JSON text
@@ -539,6 +532,7 @@ impl ser::SerializeStructVariant for Unreachable {
539
532
mod tests {
540
533
541
534
use super :: to_string;
535
+ use serde:: { Serialize , Serializer } ;
542
536
use serde_derive:: { Deserialize , Serialize } ;
543
537
544
538
#[ test]
@@ -869,6 +863,32 @@ mod tests {
869
863
assert_eq ! ( to_string( " \u{001f} " ) . unwrap( ) , r#"" \u001F ""# ) ;
870
864
}
871
865
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
+
872
892
#[ test]
873
893
fn newtype ( ) {
874
894
#[ derive( Serialize ) ]
0 commit comments