about summary refs log tree commit diff
path: root/src/libcollections/string.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/libcollections/string.rs')
-rw-r--r--src/libcollections/string.rs38
1 files changed, 37 insertions, 1 deletions
diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs
index b5ed7e6a077..3c75198a368 100644
--- a/src/libcollections/string.rs
+++ b/src/libcollections/string.rs
@@ -808,6 +808,20 @@ pub trait IntoString {
     fn into_string(self) -> String;
 }
 
+/// A generic trait for converting a value to a string
+pub trait ToString {
+    /// Converts the value of `self` to an owned string
+    fn to_string(&self) -> String;
+}
+
+impl<T: fmt::Show> ToString for T {
+    fn to_string(&self) -> String {
+        let mut buf = Vec::<u8>::new();
+        let _ = format_args!(|args| fmt::write(&mut buf, args), "{}", self);
+        String::from_utf8(buf).unwrap()
+    }
+}
+
 /// Unsafe operations
 #[unstable = "waiting on raw module conventions"]
 pub mod raw {
@@ -873,7 +887,7 @@ mod tests {
 
     use str;
     use str::{Str, StrPrelude, Owned};
-    use super::{as_string, String};
+    use super::{as_string, String, ToString};
     use vec::Vec;
     use slice::CloneSliceAllocPrelude;
 
@@ -1177,6 +1191,28 @@ mod tests {
         assert_eq!("oob", s[1..4]);
     }
 
+    #[test]
+    fn test_simple_types() {
+        assert_eq!(1i.to_string(), "1".to_string());
+        assert_eq!((-1i).to_string(), "-1".to_string());
+        assert_eq!(200u.to_string(), "200".to_string());
+        assert_eq!(2u8.to_string(), "2".to_string());
+        assert_eq!(true.to_string(), "true".to_string());
+        assert_eq!(false.to_string(), "false".to_string());
+        assert_eq!(().to_string(), "()".to_string());
+        assert_eq!(("hi".to_string()).to_string(), "hi".to_string());
+    }
+
+    #[test]
+    fn test_vectors() {
+        let x: Vec<int> = vec![];
+        assert_eq!(x.to_string(), "[]".to_string());
+        assert_eq!((vec![1i]).to_string(), "[1]".to_string());
+        assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]".to_string());
+        assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() ==
+               "[[], [1], [1, 1]]".to_string());
+    }
+
     #[bench]
     fn bench_with_capacity(b: &mut Bencher) {
         b.iter(|| {