rust/src/libstd/smallintmap.rs

83 lines
1.7 KiB
Rust
Raw Normal View History

2011-10-26 18:24:31 -05:00
/*
Module: smallintmap
2011-10-26 18:24:31 -05:00
A simple map based on a vector for small integer keys. Space requirements
are O(highest integer key).
*/
import core::option;
import core::option::{some, none};
// FIXME: Should not be @; there's a bug somewhere in rustc that requires this
// to be.
2011-10-26 18:24:31 -05:00
/*
Type: smallintmap
*/
type smallintmap<T> = @{mutable v: [mutable option::t<T>]};
2011-10-26 18:24:31 -05:00
/*
Function: mk
Create a smallintmap
*/
fn mk<T>() -> smallintmap<T> {
let v: [mutable option::t<T>] = [mutable];
2011-07-27 07:19:39 -05:00
ret @{mutable v: v};
}
2011-10-26 18:24:31 -05:00
/*
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));
}
2011-10-26 18:24:31 -05:00
/*
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>;
}
2011-10-26 18:24:31 -05:00
/*
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; }
}
}
2011-10-26 18:24:31 -05:00
/*
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));
}
2011-10-26 18:24:31 -05:00
// 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);
2011-07-27 07:19:39 -05:00
}