@@ -15,6 +15,10 @@ The `ToStr` trait for converting to strings
15
15
*/
16
16
17
17
use str;
18
+ use hashmap:: HashMap ;
19
+ use container:: Map ;
20
+ use hash:: Hash ;
21
+ use cmp:: Eq ;
18
22
19
23
pub trait ToStr {
20
24
fn to_str ( & self ) -> ~str ;
@@ -46,6 +50,26 @@ impl<A:ToStr> ToStr for (A,) {
46
50
}
47
51
}
48
52
53
+ impl < A : ToStr +Hash +Eq , B : ToStr +Hash +Eq > ToStr for HashMap < A , B > {
54
+ #[ inline( always) ]
55
+ fn to_str ( & self ) -> ~str {
56
+ let mut acc = ~"{ ", first = true;
57
+ for self.each |key, value| {
58
+ if first {
59
+ first = false;
60
+ }
61
+ else {
62
+ str::push_str(&mut acc, ~" , ");
63
+ }
64
+ str::push_str(&mut acc, key.to_str());
65
+ str::push_str(&mut acc, ~" : ");
66
+ str::push_str(&mut acc, value.to_str());
67
+ }
68
+ str::push_char(&mut acc, '}');
69
+ acc
70
+ }
71
+ }
72
+
49
73
impl<A:ToStr,B:ToStr> ToStr for (A, B) {
50
74
#[inline(always)]
51
75
fn to_str(&self) -> ~str {
@@ -149,4 +173,16 @@ mod tests {
149
173
assert!((~[~[], ~[1], ~[1, 1]]).to_str() ==
150
174
~" [ [ ] , [ 1 ] , [ 1 , 1 ] ] ");
151
175
}
176
+
177
+ #[test]
178
+ fn test_hashmap() {
179
+ let mut table: HashMap<int, int> = HashMap::new();
180
+ let mut empty: HashMap<int, int> = HashMap::new();
181
+
182
+ table.insert(3, 4);
183
+ table.insert(1, 2);
184
+
185
+ assert!(table.to_str() == ~" { 1 : 2 , 3 : 4 } ");
186
+ assert!(empty.to_str() == ~" { } " ) ;
187
+ }
152
188
}
0 commit comments