about summary refs log tree commit diff
path: root/src/libstd/smallintmap.rs
blob: d57f553b68fa0c7be52ab4e5df1a919b8fd97c1b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
Module: smallintmap

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
*/
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);
}