Skip to content

Commit aa232a5

Browse files
committed
Merge pull request #2846 from gwillen/1c882842e06431767676887f97f9dcc0ee50a7b9
Add map::clear
2 parents a7f6e00 + 1c88284 commit aa232a5

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/libstd/map.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ iface map<K, V: copy> {
6060
*/
6161
fn remove(K) -> option<V>;
6262

63+
/// Clear the map, removing all key/value pairs.
64+
fn clear();
65+
6366
/// Iterate over all the key/value pairs in the map
6467
fn each(fn(K, V) -> bool);
6568

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

81+
const initial_capacity: uint = 32u; // 2^5
82+
7883
type entry<K, V> = {
7984
hash: uint,
8085
key: K,
@@ -255,6 +260,11 @@ mod chained {
255260
}
256261
}
257262

263+
fn clear() {
264+
self.count = 0u;
265+
self.chains = chains(initial_capacity);
266+
}
267+
258268
fn each(blk: fn(K,V) -> bool) {
259269
for self.each_entry |entry| {
260270
if !blk(entry.key, copy entry.value) { break; }
@@ -271,7 +281,6 @@ mod chained {
271281
}
272282

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

621+
#[test]
622+
fn test_clear() {
623+
let key = "k";
624+
let map = map::hashmap::<str, str>(str::hash, str::eq);
625+
map.insert(key, "val");
626+
assert (map.size() == 1);
627+
assert (map.contains_key(key));
628+
map.clear();
629+
assert (map.size() == 0);
630+
assert (!map.contains_key(key));
631+
}
632+
612633
#[test]
613634
fn test_hash_from_vec() {
614635
let map = map::hash_from_strs(~[

src/libstd/smallintmap.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,9 @@ impl <V: copy> of map::map<uint, V> for smallintmap<V> {
7373
self.v.set_elt(key, none);
7474
old
7575
}
76+
fn clear() {
77+
self.v.set(~[mut]);
78+
}
7679
fn contains_key(&&key: uint) -> bool {
7780
contains_key(self, key)
7881
}

0 commit comments

Comments
 (0)