Skip to content

Commit d807f00

Browse files
committed
Add to_str() for HashMaps, and some basic tests as well.
1 parent fdf601e commit d807f00

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/libcore/to_str.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ The `ToStr` trait for converting to strings
1515
*/
1616

1717
use str;
18+
use hashmap::HashMap;
19+
use container::Map;
20+
use hash::Hash;
21+
use cmp::Eq;
1822

1923
pub trait ToStr {
2024
fn to_str(&self) -> ~str;
@@ -46,6 +50,26 @@ impl<A:ToStr> ToStr for (A,) {
4650
}
4751
}
4852

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+
4973
impl<A:ToStr,B:ToStr> ToStr for (A, B) {
5074
#[inline(always)]
5175
fn to_str(&self) -> ~str {
@@ -149,4 +173,16 @@ mod tests {
149173
assert!((~[~[], ~[1], ~[1, 1]]).to_str() ==
150174
~"[[], [1], [1, 1]]");
151175
}
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+
}
152188
}

0 commit comments

Comments
 (0)