]> git.lizzy.rs Git - rust.git/blob - src/libstd/to_str.rs
auto merge of #12319 : SimonSapin/rust/build-symlink, 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 option::{Some, None};
18 use str::OwnedStr;
19 use hashmap::HashMap;
20 use hashmap::HashSet;
21 use hash::Hash;
22 use iter::Iterator;
23 use cmp::Eq;
24 use vec::ImmutableVector;
25
26 /// A generic trait for converting a value to a string
27 pub trait ToStr {
28     /// Converts the value of `self` to an owned string
29     fn to_str(&self) -> ~str;
30 }
31
32 /// Trait for converting a type to a string, consuming it in the process.
33 pub trait IntoStr {
34     /// Consume and convert to a string.
35     fn into_str(self) -> ~str;
36 }
37
38 impl ToStr for () {
39     #[inline]
40     fn to_str(&self) -> ~str { ~"()" }
41 }
42
43 impl<A:ToStr+Hash+Eq, B:ToStr> ToStr for HashMap<A, B> {
44     #[inline]
45     fn to_str(&self) -> ~str {
46         let mut acc = ~"{";
47         let mut first = true;
48         for (key, value) in self.iter() {
49             if first {
50                 first = false;
51             }
52             else {
53                 acc.push_str(", ");
54             }
55             acc.push_str(key.to_str());
56             acc.push_str(": ");
57             acc.push_str(value.to_str());
58         }
59         acc.push_char('}');
60         acc
61     }
62 }
63
64 impl<A:ToStr+Hash+Eq> ToStr for HashSet<A> {
65     #[inline]
66     fn to_str(&self) -> ~str {
67         let mut acc = ~"{";
68         let mut first = true;
69         for element in self.iter() {
70             if first {
71                 first = false;
72             }
73             else {
74                 acc.push_str(", ");
75             }
76             acc.push_str(element.to_str());
77         }
78         acc.push_char('}');
79         acc
80     }
81 }
82
83 impl<'a,A:ToStr> ToStr for &'a [A] {
84     #[inline]
85     fn to_str(&self) -> ~str {
86         let mut acc = ~"[";
87         let mut first = true;
88         for elt in self.iter() {
89             if first {
90                 first = false;
91             }
92             else {
93                 acc.push_str(", ");
94             }
95             acc.push_str(elt.to_str());
96         }
97         acc.push_char(']');
98         acc
99     }
100 }
101
102 impl<A:ToStr> ToStr for ~[A] {
103     #[inline]
104     fn to_str(&self) -> ~str {
105         let mut acc = ~"[";
106         let mut first = true;
107         for elt in self.iter() {
108             if first {
109                 first = false;
110             }
111             else {
112                 acc.push_str(", ");
113             }
114             acc.push_str(elt.to_str());
115         }
116         acc.push_char(']');
117         acc
118     }
119 }
120
121 #[cfg(test)]
122 mod tests {
123     use hashmap::HashMap;
124     use hashmap::HashSet;
125     use container::{MutableSet, MutableMap};
126     use super::*;
127
128     #[test]
129     fn test_simple_types() {
130         assert_eq!(1i.to_str(), ~"1");
131         assert_eq!((-1i).to_str(), ~"-1");
132         assert_eq!(200u.to_str(), ~"200");
133         assert_eq!(2u8.to_str(), ~"2");
134         assert_eq!(true.to_str(), ~"true");
135         assert_eq!(false.to_str(), ~"false");
136         assert_eq!(().to_str(), ~"()");
137         assert_eq!((~"hi").to_str(), ~"hi");
138     }
139
140     #[test]
141     fn test_vectors() {
142         let x: ~[int] = ~[];
143         assert_eq!(x.to_str(), ~"[]");
144         assert_eq!((~[1]).to_str(), ~"[1]");
145         assert_eq!((~[1, 2, 3]).to_str(), ~"[1, 2, 3]");
146         assert!((~[~[], ~[1], ~[1, 1]]).to_str() ==
147                ~"[[], [1], [1, 1]]");
148     }
149
150     struct StructWithToStrWithoutEqOrHash {
151         value: int
152     }
153
154     impl ToStr for StructWithToStrWithoutEqOrHash {
155         fn to_str(&self) -> ~str {
156             format!("s{}", self.value)
157         }
158     }
159
160     #[test]
161     fn test_hashmap() {
162         let mut table: HashMap<int, StructWithToStrWithoutEqOrHash> = HashMap::new();
163         let empty: HashMap<int, StructWithToStrWithoutEqOrHash> = HashMap::new();
164
165         table.insert(3, StructWithToStrWithoutEqOrHash { value: 4 });
166         table.insert(1, StructWithToStrWithoutEqOrHash { value: 2 });
167
168         let table_str = table.to_str();
169
170         assert!(table_str == ~"{1: s2, 3: s4}" || table_str == ~"{3: s4, 1: s2}");
171         assert_eq!(empty.to_str(), ~"{}");
172     }
173
174     #[test]
175     fn test_hashset() {
176         let mut set: HashSet<int> = HashSet::new();
177         let empty_set: HashSet<int> = HashSet::new();
178
179         set.insert(1);
180         set.insert(2);
181
182         let set_str = set.to_str();
183
184         assert!(set_str == ~"{1, 2}" || set_str == ~"{2, 1}");
185         assert_eq!(empty_set.to_str(), ~"{}");
186     }
187 }