Skip to content

Commit

Permalink
Add to_str() for HashMaps, and some basic tests as well.
Browse files Browse the repository at this point in the history
  • Loading branch information
samebchase committed May 10, 2013
1 parent fdf601e commit d807f00
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/libcore/to_str.rs
Expand Up @@ -15,6 +15,10 @@ The `ToStr` trait for converting to strings
*/

use str;
use hashmap::HashMap;
use container::Map;
use hash::Hash;
use cmp::Eq;

pub trait ToStr {
fn to_str(&self) -> ~str;
Expand Down Expand Up @@ -46,6 +50,26 @@ impl<A:ToStr> ToStr for (A,) {
}
}

impl<A:ToStr+Hash+Eq, B:ToStr+Hash+Eq> ToStr for HashMap<A, B> {
#[inline(always)]
fn to_str(&self) -> ~str {
let mut acc = ~"{", first = true;
for self.each |key, value| {
if first {
first = false;
}
else {
str::push_str(&mut acc, ~", ");
}
str::push_str(&mut acc, key.to_str());
str::push_str(&mut acc, ~" : ");
str::push_str(&mut acc, value.to_str());
}
str::push_char(&mut acc, '}');
acc
}
}
impl<A:ToStr,B:ToStr> ToStr for (A, B) {
#[inline(always)]
fn to_str(&self) -> ~str {
Expand Down Expand Up @@ -149,4 +173,16 @@ mod tests {
assert!((~[~[], ~[1], ~[1, 1]]).to_str() ==
~"[[], [1], [1, 1]]");
}

#[test]
fn test_hashmap() {
let mut table: HashMap<int, int> = HashMap::new();
let mut empty: HashMap<int, int> = HashMap::new();

table.insert(3, 4);
table.insert(1, 2);

assert!(table.to_str() == ~"{1 : 2, 3 : 4}");
assert!(empty.to_str() == ~"{}");
}
}

0 comments on commit d807f00

Please sign in to comment.