Skip to content

Commit

Permalink
Merge pull request #2846 from gwillen/1c882842e06431767676887f97f9dcc…
Browse files Browse the repository at this point in the history
…0ee50a7b9

Add map::clear
  • Loading branch information
brson committed Jul 9, 2012
2 parents a7f6e00 + 1c88284 commit aa232a5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/libstd/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ iface map<K, V: copy> {
*/
fn remove(K) -> option<V>;

/// Clear the map, removing all key/value pairs.
fn clear();

/// Iterate over all the key/value pairs in the map
fn each(fn(K, V) -> bool);

Expand All @@ -75,6 +78,8 @@ iface map<K, V: copy> {
mod chained {
export t, mk, hashmap;

const initial_capacity: uint = 32u; // 2^5

type entry<K, V> = {
hash: uint,
key: K,
Expand Down Expand Up @@ -255,6 +260,11 @@ mod chained {
}
}

fn clear() {
self.count = 0u;
self.chains = chains(initial_capacity);
}

fn each(blk: fn(K,V) -> bool) {
for self.each_entry |entry| {
if !blk(entry.key, copy entry.value) { break; }
Expand All @@ -271,7 +281,6 @@ mod chained {
}

fn mk<K, V: copy>(hasher: hashfn<K>, eqer: eqfn<K>) -> t<K,V> {
let initial_capacity: uint = 32u; // 2^5
let slf: t<K, V> = @{mut count: 0u,
mut chains: chains(initial_capacity),
hasher: hasher,
Expand Down Expand Up @@ -609,6 +618,18 @@ mod tests {
assert (option::get(map.find(key)) == "val");
}

#[test]
fn test_clear() {
let key = "k";
let map = map::hashmap::<str, str>(str::hash, str::eq);
map.insert(key, "val");
assert (map.size() == 1);
assert (map.contains_key(key));
map.clear();
assert (map.size() == 0);
assert (!map.contains_key(key));
}

#[test]
fn test_hash_from_vec() {
let map = map::hash_from_strs(~[
Expand Down
3 changes: 3 additions & 0 deletions src/libstd/smallintmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ impl <V: copy> of map::map<uint, V> for smallintmap<V> {
self.v.set_elt(key, none);
old
}
fn clear() {
self.v.set(~[mut]);
}
fn contains_key(&&key: uint) -> bool {
contains_key(self, key)
}
Expand Down

0 comments on commit aa232a5

Please sign in to comment.