]> git.lizzy.rs Git - rust.git/blob - src/libstd/to_str.rs
auto merge of #12445 : huonw/rust/less-unsafe, 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
19 /// A generic trait for converting a value to a string
20 pub trait ToStr {
21     /// Converts the value of `self` to an owned string
22     fn to_str(&self) -> ~str;
23 }
24
25 /// Trait for converting a type to a string, consuming it in the process.
26 pub trait IntoStr {
27     /// Consume and convert to a string.
28     fn into_str(self) -> ~str;
29 }
30
31 impl<T: fmt::Show> ToStr for T {
32     fn to_str(&self) -> ~str { format!("{}", *self) }
33 }
34
35 #[cfg(test)]
36 mod tests {
37     use super::*;
38
39     #[test]
40     fn test_simple_types() {
41         assert_eq!(1i.to_str(), ~"1");
42         assert_eq!((-1i).to_str(), ~"-1");
43         assert_eq!(200u.to_str(), ~"200");
44         assert_eq!(2u8.to_str(), ~"2");
45         assert_eq!(true.to_str(), ~"true");
46         assert_eq!(false.to_str(), ~"false");
47         assert_eq!(().to_str(), ~"()");
48         assert_eq!((~"hi").to_str(), ~"hi");
49     }
50
51     #[test]
52     fn test_vectors() {
53         let x: ~[int] = ~[];
54         assert_eq!(x.to_str(), ~"[]");
55         assert_eq!((~[1]).to_str(), ~"[1]");
56         assert_eq!((~[1, 2, 3]).to_str(), ~"[1, 2, 3]");
57         assert!((~[~[], ~[1], ~[1, 1]]).to_str() ==
58                ~"[[], [1], [1, 1]]");
59     }
60 }