about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPatrick Walton <pcwalton@mimiga.net>2011-06-03 16:14:29 -0700
committerPatrick Walton <pcwalton@mimiga.net>2011-06-03 16:15:14 -0700
commitcb4c969ba6ec61007ac1bbdaeed7eb5f21859949 (patch)
tree5650e438fd25d75c682883156869f848403bbb81 /src
parent088ab03fdbdd2fad29b678f5eeaadde4e15cb205 (diff)
downloadrust-cb4c969ba6ec61007ac1bbdaeed7eb5f21859949.tar.gz
rust-cb4c969ba6ec61007ac1bbdaeed7eb5f21859949.zip
rustc: Add a "smallintmap" implementation
Diffstat (limited to 'src')
-rw-r--r--src/lib/smallintmap.rs40
-rw-r--r--src/lib/std.rc1
-rw-r--r--src/lib/vec.rs13
3 files changed, 54 insertions, 0 deletions
diff --git a/src/lib/smallintmap.rs b/src/lib/smallintmap.rs
new file mode 100644
index 00000000000..ca586eb6f05
--- /dev/null
+++ b/src/lib/smallintmap.rs
@@ -0,0 +1,40 @@
+/// A simple map based on a vector for small integer keys. Space requirements
+/// are O(highest integer key).
+
+import option::none;
+import option::some;
+
+type smallintmap[T] = rec(mutable vec[mutable option::t[T]] v);
+
+fn mk[T]() -> smallintmap[T] {
+    let vec[mutable option::t[T]] v = [mutable];
+    ret rec(mutable v=v);
+}
+
+fn insert[T](&smallintmap[T] m, uint key, &T val) {
+    vec::grow_set[option::t[T]](m.v, key, none[T], some[T](val));
+}
+
+fn find[T](&smallintmap[T] m, uint key) -> option::t[T] {
+    if (key < vec::len[option::t[T]](m.v)) { ret m.v.(key); }
+    ret none[T];
+}
+
+fn get[T](&smallintmap[T] m, uint key) -> T {
+    alt (find[T](m, key)) {
+        case (none[T]) {
+            log_err "smallintmap::get(): key not present";
+            fail;
+        }
+        case (some[T](?v)) { ret v; }
+    }
+}
+
+fn contains_key[T](&smallintmap[T] m, uint key) -> bool {
+    ret !option::is_none(find[T](m, key));
+}
+
+fn truncate[T](&smallintmap[T] m, uint len) {
+    m.v = vec::slice_mut[option::t[T]](m.v, 0u, len);
+}
+
diff --git a/src/lib/std.rc b/src/lib/std.rc
index c0839ce9098..3619ede40f8 100644
--- a/src/lib/std.rc
+++ b/src/lib/std.rc
@@ -76,6 +76,7 @@ mod box;
 mod getopts;
 mod term;
 mod time;
+mod smallintmap;
 
 // Local Variables:
 // mode: rust;
diff --git a/src/lib/vec.rs b/src/lib/vec.rs
index 969fca9a17e..8259e494e25 100644
--- a/src/lib/vec.rs
+++ b/src/lib/vec.rs
@@ -163,6 +163,19 @@ fn slice[T](array[T] v, uint start, uint end) -> vec[T] {
     ret result;
 }
 
+// FIXME: Should go away eventually.
+fn slice_mut[T](array[T] v, uint start, uint end) -> vec[mutable T] {
+    assert (start <= end);
+    assert (end <= len[T](v));
+    auto result = alloc_mut[T](end - start);
+    let uint i = start;
+    while (i < end) {
+        result += [mutable v.(i)];
+        i += 1u;
+    }
+    ret result;
+}
+
 fn shift[T](&mutable array[T] v) -> T {
     auto ln = len[T](v);
     assert (ln > 0u);