]> git.lizzy.rs Git - rust.git/blob - src/libstd/to_str.rs
auto merge of #14483 : ahmedcharles/rust/patbox, r=alexcrichton
[rust.git] / src / libstd / to_str.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /*!
12
13 The `ToStr` trait for converting to strings
14
15 */
16
17 use fmt;
18 use string::String;
19
20 /// A generic trait for converting a value to a string
21 pub trait ToStr {
22     /// Converts the value of `self` to an owned string
23     fn to_str(&self) -> String;
24 }
25
26 /// Trait for converting a type to a string, consuming it in the process.
27 pub trait IntoStr {
28     /// Consume and convert to a string.
29     fn into_str(self) -> String;
30 }
31
32 impl<T: fmt::Show> ToStr for T {
33     fn to_str(&self) -> String {
34         format!("{}", *self)
35     }
36 }
37
38 #[cfg(test)]
39 mod tests {
40     use super::*;
41     use str::StrAllocating;
42
43     #[test]
44     fn test_simple_types() {
45         assert_eq!(1i.to_str(), "1".to_string());
46         assert_eq!((-1i).to_str(), "-1".to_string());
47         assert_eq!(200u.to_str(), "200".to_string());
48         assert_eq!(2u8.to_str(), "2".to_string());
49         assert_eq!(true.to_str(), "true".to_string());
50         assert_eq!(false.to_str(), "false".to_string());
51         assert_eq!(().to_str(), "()".to_string());
52         assert_eq!(("hi".to_string()).to_str(), "hi".to_string());
53     }
54
55     #[test]
56     fn test_vectors() {
57         let x: ~[int] = box [];
58         assert_eq!(x.to_str(), "[]".to_string());
59         assert_eq!((box [1]).to_str(), "[1]".to_string());
60         assert_eq!((box [1, 2, 3]).to_str(), "[1, 2, 3]".to_string());
61         assert!((box [box [], box [1], box [1, 1]]).to_str() ==
62                "[[], [1], [1, 1]]".to_string());
63     }
64 }