summary refs log tree commit diff
path: root/src/libstd/smallintmap.rs
diff options
context:
space:
mode:
authorGraydon Hoare <graydon@mozilla.com>2011-12-05 16:46:37 -0800
committerGraydon Hoare <graydon@mozilla.com>2011-12-06 12:13:04 -0800
commit447414f00774d37d934867f5a476cf00e1f95423 (patch)
treed328aa66e62f345cb5d7c7d01c8215e8c9324e79 /src/libstd/smallintmap.rs
parentb513a5a5001b850a153db12d9621d00a70ff929a (diff)
downloadrust-447414f00774d37d934867f5a476cf00e1f95423.tar.gz
rust-447414f00774d37d934867f5a476cf00e1f95423.zip
Establish 'core' library separate from 'std'.
Diffstat (limited to 'src/libstd/smallintmap.rs')
-rw-r--r--src/libstd/smallintmap.rs81
1 files changed, 81 insertions, 0 deletions
diff --git a/src/libstd/smallintmap.rs b/src/libstd/smallintmap.rs
new file mode 100644
index 00000000000..4702a2adab4
--- /dev/null
+++ b/src/libstd/smallintmap.rs
@@ -0,0 +1,81 @@
+/*
+Module: smallintmap
+
+A simple map based on a vector for small integer keys. Space requirements
+are O(highest integer key).
+*/
+import option::{some, none};
+
+// FIXME: Should not be @; there's a bug somewhere in rustc that requires this
+// to be.
+/*
+Type: smallintmap
+*/
+type smallintmap<T> = @{mutable v: [mutable option::t<T>]};
+
+/*
+Function: mk
+
+Create a smallintmap
+*/
+fn mk<T>() -> smallintmap<T> {
+    let v: [mutable option::t<T>] = [mutable];
+    ret @{mutable v: v};
+}
+
+/*
+Function: insert
+
+Add a value to the map. If the map already contains a value for
+the specified key then the original value is replaced.
+*/
+fn insert<copy T>(m: smallintmap<T>, key: uint, val: T) {
+    vec::grow_set::<option::t<T>>(m.v, key, none::<T>, some::<T>(val));
+}
+
+/*
+Function: find
+
+Get the value for the specified key. If the key does not exist
+in the map then returns none.
+*/
+fn find<copy T>(m: smallintmap<T>, key: uint) -> option::t<T> {
+    if key < vec::len::<option::t<T>>(m.v) { ret m.v[key]; }
+    ret none::<T>;
+}
+
+/*
+Method: get
+
+Get the value for the specified key
+
+Failure:
+
+If the key does not exist in the map
+*/
+fn get<copy T>(m: smallintmap<T>, key: uint) -> T {
+    alt find(m, key) {
+      none. { log_err "smallintmap::get(): key not present"; fail; }
+      some(v) { ret v; }
+    }
+}
+
+/*
+Method: contains_key
+
+Returns true if the map contains a value for the specified key
+*/
+fn contains_key<copy T>(m: smallintmap<T>, key: uint) -> bool {
+    ret !option::is_none(find::<T>(m, key));
+}
+
+// FIXME: Are these really useful?
+
+fn truncate<copy T>(m: smallintmap<T>, len: uint) {
+    m.v = vec::slice_mut::<option::t<T>>(m.v, 0u, len);
+}
+
+fn max_key<T>(m: smallintmap<T>) -> uint {
+    ret vec::len::<option::t<T>>(m.v);
+}
+