]> git.lizzy.rs Git - rust.git/blob - src/libstd/to_str.rs
auto merge of #9662 : vadimcn/rust/package-runtime-deps, r=brson
[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 ToStrConsume {
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> ToStr for (A,) {
44     #[inline]
45     fn to_str(&self) -> ~str {
46         match *self {
47             (ref a,) => {
48                 format!("({},)", (*a).to_str())
49             }
50         }
51     }
52 }
53
54 impl<A:ToStr+Hash+Eq, B:ToStr> ToStr for HashMap<A, B> {
55     #[inline]
56     fn to_str(&self) -> ~str {
57         let mut acc = ~"{";
58         let mut first = true;
59         for (key, value) in self.iter() {
60             if first {
61                 first = false;
62             }
63             else {
64                 acc.push_str(", ");
65             }
66             acc.push_str(key.to_str());
67             acc.push_str(": ");
68             acc.push_str(value.to_str());
69         }
70         acc.push_char('}');
71         acc
72     }
73 }
74
75 impl<A:ToStr+Hash+Eq> ToStr for HashSet<A> {
76     #[inline]
77     fn to_str(&self) -> ~str {
78         let mut acc = ~"{";
79         let mut first = true;
80         for element in self.iter() {
81             if first {
82                 first = false;
83             }
84             else {
85                 acc.push_str(", ");
86             }
87             acc.push_str(element.to_str());
88         }
89         acc.push_char('}');
90         acc
91     }
92 }
93
94 impl<A:ToStr,B:ToStr> ToStr for (A, B) {
95     #[inline]
96     fn to_str(&self) -> ~str {
97         // FIXME(#4653): this causes an llvm assertion
98         //let &(ref a, ref b) = self;
99         match *self {
100             (ref a, ref b) => {
101                 format!("({}, {})", (*a).to_str(), (*b).to_str())
102             }
103         }
104     }
105 }
106
107 impl<A:ToStr,B:ToStr,C:ToStr> ToStr for (A, B, C) {
108     #[inline]
109     fn to_str(&self) -> ~str {
110         // FIXME(#4653): this causes an llvm assertion
111         //let &(ref a, ref b, ref c) = self;
112         match *self {
113             (ref a, ref b, ref c) => {
114                 format!("({}, {}, {})",
115                     (*a).to_str(),
116                     (*b).to_str(),
117                     (*c).to_str()
118                 )
119             }
120         }
121     }
122 }
123
124 impl<'self,A:ToStr> ToStr for &'self [A] {
125     #[inline]
126     fn to_str(&self) -> ~str {
127         let mut acc = ~"[";
128         let mut first = true;
129         for elt in self.iter() {
130             if first {
131                 first = false;
132             }
133             else {
134                 acc.push_str(", ");
135             }
136             acc.push_str(elt.to_str());
137         }
138         acc.push_char(']');
139         acc
140     }
141 }
142
143 impl<A:ToStr> ToStr for ~[A] {
144     #[inline]
145     fn to_str(&self) -> ~str {
146         let mut acc = ~"[";
147         let mut first = true;
148         for elt in self.iter() {
149             if first {
150                 first = false;
151             }
152             else {
153                 acc.push_str(", ");
154             }
155             acc.push_str(elt.to_str());
156         }
157         acc.push_char(']');
158         acc
159     }
160 }
161
162 impl<A:ToStr> ToStr for @[A] {
163     #[inline]
164     fn to_str(&self) -> ~str {
165         let mut acc = ~"[";
166         let mut first = true;
167         for elt in self.iter() {
168             if first {
169                 first = false;
170             }
171             else {
172                 acc.push_str(", ");
173             }
174             acc.push_str(elt.to_str());
175         }
176         acc.push_char(']');
177         acc
178     }
179 }
180
181 #[cfg(test)]
182 mod tests {
183     use hashmap::HashMap;
184     use hashmap::HashSet;
185     use container::{MutableSet, MutableMap};
186     use super::*;
187
188     #[test]
189     fn test_simple_types() {
190         assert_eq!(1i.to_str(), ~"1");
191         assert_eq!((-1i).to_str(), ~"-1");
192         assert_eq!(200u.to_str(), ~"200");
193         assert_eq!(2u8.to_str(), ~"2");
194         assert_eq!(true.to_str(), ~"true");
195         assert_eq!(false.to_str(), ~"false");
196         assert_eq!(().to_str(), ~"()");
197         assert_eq!((~"hi").to_str(), ~"hi");
198         assert_eq!((@"hi").to_str(), ~"hi");
199     }
200
201     #[test]
202     fn test_tuple_types() {
203         assert_eq!((1, 2).to_str(), ~"(1, 2)");
204         assert_eq!((~"a", ~"b", false).to_str(), ~"(a, b, false)");
205         assert_eq!(((), ((), 100)).to_str(), ~"((), ((), 100))");
206     }
207
208     #[test]
209     fn test_vectors() {
210         let x: ~[int] = ~[];
211         assert_eq!(x.to_str(), ~"[]");
212         assert_eq!((~[1]).to_str(), ~"[1]");
213         assert_eq!((~[1, 2, 3]).to_str(), ~"[1, 2, 3]");
214         assert!((~[~[], ~[1], ~[1, 1]]).to_str() ==
215                ~"[[], [1], [1, 1]]");
216     }
217
218     struct StructWithToStrWithoutEqOrHash {
219         value: int
220     }
221
222     impl ToStr for StructWithToStrWithoutEqOrHash {
223         fn to_str(&self) -> ~str {
224             format!("s{}", self.value)
225         }
226     }
227
228     #[test]
229     fn test_hashmap() {
230         let mut table: HashMap<int, StructWithToStrWithoutEqOrHash> = HashMap::new();
231         let empty: HashMap<int, StructWithToStrWithoutEqOrHash> = HashMap::new();
232
233         table.insert(3, StructWithToStrWithoutEqOrHash { value: 4 });
234         table.insert(1, StructWithToStrWithoutEqOrHash { value: 2 });
235
236         let table_str = table.to_str();
237
238         assert!(table_str == ~"{1: s2, 3: s4}" || table_str == ~"{3: s4, 1: s2}");
239         assert_eq!(empty.to_str(), ~"{}");
240     }
241
242     #[test]
243     fn test_hashset() {
244         let mut set: HashSet<int> = HashSet::new();
245         let empty_set: HashSet<int> = HashSet::new();
246
247         set.insert(1);
248         set.insert(2);
249
250         let set_str = set.to_str();
251
252         assert!(set_str == ~"{1, 2}" || set_str == ~"{2, 1}");
253         assert_eq!(empty_set.to_str(), ~"{}");
254     }
255 }