about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorGlenn Willen <gwillen@nerdnet.org>2012-07-08 16:04:57 -0700
committerGlenn Willen <gwillen@nerdnet.org>2012-07-08 16:06:48 -0700
commit1c882842e06431767676887f97f9dcc0ee50a7b9 (patch)
tree902829cd0cff2b374ed3ea21a90cf0963225593c /src/libstd
parentd95ab538c1c503c76b1d10211dd60c9d29091a2f (diff)
Add clear() to the map interface.
Add clear to the map interface, and implement it in hashmap and smallintmap.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/map.rs23
-rw-r--r--src/libstd/smallintmap.rs3
2 files changed, 25 insertions, 1 deletions
diff --git a/src/libstd/map.rs b/src/libstd/map.rs
index 46f2ca053ad..8a2089c6f2b 100644
--- a/src/libstd/map.rs
+++ b/src/libstd/map.rs
@@ -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);
 
@@ -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,
@@ -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; }
@@ -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,
@@ -610,6 +619,18 @@ mod tests {
     }
 
     #[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(~[
             ("a", 1),
diff --git a/src/libstd/smallintmap.rs b/src/libstd/smallintmap.rs
index 9fb4be4804d..1d17ba0dbb4 100644
--- a/src/libstd/smallintmap.rs
+++ b/src/libstd/smallintmap.rs
@@ -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)
     }