@@ -808,6 +808,20 @@ pub trait IntoString {
808
808
fn into_string ( self ) -> String ;
809
809
}
810
810
811
+ /// A generic trait for converting a value to a string
812
+ pub trait ToString {
813
+ /// Converts the value of `self` to an owned string
814
+ fn to_string ( & self ) -> String ;
815
+ }
816
+
817
+ impl < T : fmt:: Show > ToString for T {
818
+ fn to_string ( & self ) -> String {
819
+ let mut buf = Vec :: < u8 > :: new ( ) ;
820
+ let _ = format_args ! ( |args| fmt:: write( & mut buf, args) , "{}" , self ) ;
821
+ String :: from_utf8 ( buf) . unwrap ( )
822
+ }
823
+ }
824
+
811
825
/// Unsafe operations
812
826
#[ unstable = "waiting on raw module conventions" ]
813
827
pub mod raw {
@@ -873,7 +887,7 @@ mod tests {
873
887
874
888
use str;
875
889
use str:: { Str , StrPrelude , Owned } ;
876
- use super :: { as_string, String } ;
890
+ use super :: { as_string, String , ToString } ;
877
891
use vec:: Vec ;
878
892
use slice:: CloneSliceAllocPrelude ;
879
893
@@ -1177,6 +1191,28 @@ mod tests {
1177
1191
assert_eq ! ( "oob" , s[ 1 ..4 ] ) ;
1178
1192
}
1179
1193
1194
+ #[ test]
1195
+ fn test_simple_types ( ) {
1196
+ assert_eq ! ( 1 i. to_string( ) , "1" . to_string( ) ) ;
1197
+ assert_eq ! ( ( -1 i) . to_string( ) , "-1" . to_string( ) ) ;
1198
+ assert_eq ! ( 200 u. to_string( ) , "200" . to_string( ) ) ;
1199
+ assert_eq ! ( 2u8 . to_string( ) , "2" . to_string( ) ) ;
1200
+ assert_eq ! ( true . to_string( ) , "true" . to_string( ) ) ;
1201
+ assert_eq ! ( false . to_string( ) , "false" . to_string( ) ) ;
1202
+ assert_eq ! ( ( ) . to_string( ) , "()" . to_string( ) ) ;
1203
+ assert_eq ! ( ( "hi" . to_string( ) ) . to_string( ) , "hi" . to_string( ) ) ;
1204
+ }
1205
+
1206
+ #[ test]
1207
+ fn test_vectors ( ) {
1208
+ let x: Vec < int > = vec ! [ ] ;
1209
+ assert_eq ! ( x. to_string( ) , "[]" . to_string( ) ) ;
1210
+ assert_eq ! ( ( vec![ 1 i] ) . to_string( ) , "[1]" . to_string( ) ) ;
1211
+ assert_eq ! ( ( vec![ 1 i, 2 , 3 ] ) . to_string( ) , "[1, 2, 3]" . to_string( ) ) ;
1212
+ assert ! ( ( vec![ vec![ ] , vec![ 1 i] , vec![ 1 i, 1 ] ] ) . to_string( ) ==
1213
+ "[[], [1], [1, 1]]" . to_string( ) ) ;
1214
+ }
1215
+
1180
1216
#[ bench]
1181
1217
fn bench_with_capacity ( b : & mut Bencher ) {
1182
1218
b. iter ( || {
0 commit comments