From d807f00bfded3804d5f3d01e522dfa086871f8ed Mon Sep 17 00:00:00 2001 From: Samuel Chase Date: Sat, 11 May 2013 02:14:36 +0530 Subject: [PATCH] Add to_str() for HashMaps, and some basic tests as well. --- src/libcore/to_str.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/libcore/to_str.rs b/src/libcore/to_str.rs index 7f8e6915add1..a2c4ac991a49 100644 --- a/src/libcore/to_str.rs +++ b/src/libcore/to_str.rs @@ -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; @@ -46,6 +50,26 @@ impl ToStr for (A,) { } } +impl ToStr for HashMap { + #[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 ToStr for (A, B) { #[inline(always)] fn to_str(&self) -> ~str { @@ -149,4 +173,16 @@ mod tests { assert!((~[~[], ~[1], ~[1, 1]]).to_str() == ~"[[], [1], [1, 1]]"); } + + #[test] + fn test_hashmap() { + let mut table: HashMap = HashMap::new(); + let mut empty: HashMap = HashMap::new(); + + table.insert(3, 4); + table.insert(1, 2); + + assert!(table.to_str() == ~"{1 : 2, 3 : 4}"); + assert!(empty.to_str() == ~"{}"); + } }