Skip to content

Commit cb4c969

Browse files
committed
rustc: Add a "smallintmap" implementation
1 parent 088ab03 commit cb4c969

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

src/lib/smallintmap.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/// A simple map based on a vector for small integer keys. Space requirements
2+
/// are O(highest integer key).
3+
4+
import option::none;
5+
import option::some;
6+
7+
type smallintmap[T] = rec(mutable vec[mutable option::t[T]] v);
8+
9+
fn mk[T]() -> smallintmap[T] {
10+
let vec[mutable option::t[T]] v = [mutable];
11+
ret rec(mutable v=v);
12+
}
13+
14+
fn insert[T](&smallintmap[T] m, uint key, &T val) {
15+
vec::grow_set[option::t[T]](m.v, key, none[T], some[T](val));
16+
}
17+
18+
fn find[T](&smallintmap[T] m, uint key) -> option::t[T] {
19+
if (key < vec::len[option::t[T]](m.v)) { ret m.v.(key); }
20+
ret none[T];
21+
}
22+
23+
fn get[T](&smallintmap[T] m, uint key) -> T {
24+
alt (find[T](m, key)) {
25+
case (none[T]) {
26+
log_err "smallintmap::get(): key not present";
27+
fail;
28+
}
29+
case (some[T](?v)) { ret v; }
30+
}
31+
}
32+
33+
fn contains_key[T](&smallintmap[T] m, uint key) -> bool {
34+
ret !option::is_none(find[T](m, key));
35+
}
36+
37+
fn truncate[T](&smallintmap[T] m, uint len) {
38+
m.v = vec::slice_mut[option::t[T]](m.v, 0u, len);
39+
}
40+

src/lib/std.rc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ mod box;
7676
mod getopts;
7777
mod term;
7878
mod time;
79+
mod smallintmap;
7980

8081
// Local Variables:
8182
// mode: rust;

src/lib/vec.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,19 @@ fn slice[T](array[T] v, uint start, uint end) -> vec[T] {
163163
ret result;
164164
}
165165

166+
// FIXME: Should go away eventually.
167+
fn slice_mut[T](array[T] v, uint start, uint end) -> vec[mutable T] {
168+
assert (start <= end);
169+
assert (end <= len[T](v));
170+
auto result = alloc_mut[T](end - start);
171+
let uint i = start;
172+
while (i < end) {
173+
result += [mutable v.(i)];
174+
i += 1u;
175+
}
176+
ret result;
177+
}
178+
166179
fn shift[T](&mutable array[T] v) -> T {
167180
auto ln = len[T](v);
168181
assert (ln > 0u);

0 commit comments

Comments
 (0)