#[doc = " 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. type smallintmap = @{mutable v: [mutable option]}; #[doc = "Create a smallintmap"] fn mk() -> smallintmap { let v: [mutable option] = [mutable]; ret @{mutable v: v}; } #[doc = " 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(m: smallintmap, key: uint, val: T) { vec::grow_set::>(m.v, key, none::, some::(val)); } #[doc = " Get the value for the specified key. If the key does not exist in the map then returns none "] fn find(m: smallintmap, key: uint) -> option { if key < vec::len::>(m.v) { ret m.v[key]; } ret none::; } #[doc = " Get the value for the specified key # Failure If the key does not exist in the map "] fn get(m: smallintmap, key: uint) -> T { alt find(m, key) { none { #error("smallintmap::get(): key not present"); fail; } some(v) { ret v; } } } #[doc = " Returns true if the map contains a value for the specified key "] fn contains_key(m: smallintmap, key: uint) -> bool { ret !option::is_none(find::(m, key)); } // FIXME: Are these really useful? fn truncate(m: smallintmap, len: uint) { m.v = vec::to_mut(vec::slice::>(m.v, 0u, len)); } fn max_key(m: smallintmap) -> uint { ret vec::len::>(m.v); } #[doc = "Implements the map::map interface for smallintmap"] impl of map::map for smallintmap { fn size() -> uint { let mut sz = 0u; for item in self.v { alt item { some(_) { sz += 1u; } _ {} } } sz } fn insert(&&key: uint, value: V) -> bool { let exists = contains_key(self, key); insert(self, key, value); ret !exists; } fn remove(&&key: uint) -> option { if key >= vec::len(self.v) { ret none; } let old = self.v[key]; self.v[key] = none; old } fn contains_key(&&key: uint) -> bool { contains_key(self, key) } fn get(&&key: uint) -> V { get(self, key) } fn find(&&key: uint) -> option { find(self, key) } fn rehash() { fail } fn items(it: fn(&&uint, V)) { let mut idx = 0u; for item in self.v { alt item { some(elt) { it(idx, elt); } none { } } idx += 1u; } } fn keys(it: fn(&&uint)) { let mut idx = 0u; for item in self.v { if item != none { it(idx); } idx += 1u; } } fn values(it: fn(V)) { for item in self.v { alt item { some(elt) { it(elt); } _ {} } } } } #[doc = "Cast the given smallintmap to a map::map"] fn as_map(s: smallintmap) -> map::map { s as map::map:: }