Add to_str for hashmap.

This commit is contained in:
Glenn Willen
2012-07-13 03:01:26 -04:00
committed by Graydon Hoare
parent 06ac0c2b1d
commit 28519c8ef6
+31 -1
View File
@@ -1,6 +1,8 @@
//! A map type
import chained::hashmap;
import io::writer_util;
import to_str::to_str;
export hashmap, hashfn, eqfn, set, map, chained, hashmap, str_hash;
export box_str_hash;
export bytes_hash, int_hash, uint_hash, set_add;
@@ -98,6 +100,7 @@ enum chain<K, V> {
hasher: hashfn<K>,
eqer: eqfn<K>
};
type t<K, V> = @hashmap_<K, V>;
enum hashmap_<K, V> {
hashmap_(@hashmap__<K, V>)
@@ -111,7 +114,7 @@ enum search_result<K, V> {
found_after(@entry<K,V>, @entry<K,V>)
}
impl private_methods<K, V: copy> for t<K, V> {
impl private_methods<K, V: copy> for hashmap_<K, V> {
fn search_rem(k: K, h: uint, idx: uint,
e_root: @entry<K,V>) -> search_result<K,V> {
let mut e0 = e_root;
@@ -285,6 +288,33 @@ fn each_key(blk: fn(K) -> bool) { self.each(|k, _v| blk(k)) }
fn each_value(blk: fn(V) -> bool) { self.each(|_k, v| blk(v)) }
}
impl hashmap<K: to_str, V: to_str copy> of to_str for hashmap_<K, V> {
fn to_writer(wr: io::writer) {
if self.count == 0u {
wr.write_str("{}");
ret;
}
wr.write_str("{ ");
let mut first = true;
for self.each_entry |entry| {
if !first {
wr.write_str(", ");
}
first = false;
wr.write_str(entry.key.to_str());
wr.write_str(": ");
wr.write_str((copy entry.value).to_str());
};
wr.write_str(" }");
}
fn to_str() -> ~str {
do io::with_str_writer |wr| { self.to_writer(wr) }
}
}
fn chains<K,V>(nchains: uint) -> ~[mut chain<K,V>] {
ret vec::to_mut(vec::from_elem(nchains, absent));
}