2011-07-05 04:48:19 -05:00
|
|
|
// An "interner" is a data structure that associates values with uint tags and
|
|
|
|
// allows bidirectional lookup; i.e. given a value, one can easily find the
|
|
|
|
// type, and vice versa.
|
2011-12-13 18:25:51 -06:00
|
|
|
import std::map;
|
2011-09-12 18:13:28 -05:00
|
|
|
import std::map::{hashmap, hashfn, eqfn};
|
2012-05-15 15:40:01 -05:00
|
|
|
import dvec::{dvec, extensions};
|
2011-07-05 04:48:19 -05:00
|
|
|
|
2011-08-12 08:36:51 -05:00
|
|
|
type interner<T> =
|
2011-08-12 09:15:18 -05:00
|
|
|
{map: hashmap<T, uint>,
|
2012-05-15 15:40:01 -05:00
|
|
|
vect: dvec<T>,
|
2011-08-12 09:15:18 -05:00
|
|
|
hasher: hashfn<T>,
|
|
|
|
eqer: eqfn<T>};
|
2011-07-05 04:48:19 -05:00
|
|
|
|
2012-01-05 08:35:37 -06:00
|
|
|
fn mk<T: copy>(hasher: hashfn<T>, eqer: eqfn<T>) -> interner<T> {
|
2012-03-14 14:07:23 -05:00
|
|
|
let m = map::hashmap::<T, uint>(hasher, eqer);
|
2012-05-15 15:40:01 -05:00
|
|
|
ret {map: m, vect: dvec(), hasher: hasher, eqer: eqer};
|
2011-07-05 04:48:19 -05:00
|
|
|
}
|
2011-08-04 12:46:10 -05:00
|
|
|
|
2012-01-05 08:35:37 -06:00
|
|
|
fn intern<T: copy>(itr: interner<T>, val: T) -> uint {
|
2011-07-27 07:19:39 -05:00
|
|
|
alt itr.map.find(val) {
|
|
|
|
some(idx) { ret idx; }
|
2012-01-19 00:37:22 -06:00
|
|
|
none {
|
2012-05-15 15:40:01 -05:00
|
|
|
let new_idx = itr.vect.len();
|
2011-07-27 07:19:39 -05:00
|
|
|
itr.map.insert(val, new_idx);
|
2012-05-15 15:40:01 -05:00
|
|
|
itr.vect.push(val);
|
2011-07-27 07:19:39 -05:00
|
|
|
ret new_idx;
|
|
|
|
}
|
2011-07-05 04:48:19 -05:00
|
|
|
}
|
|
|
|
}
|
2011-08-04 12:46:10 -05:00
|
|
|
|
2011-09-24 18:33:26 -05:00
|
|
|
// |get| isn't "pure" in the traditional sense, because it can go from
|
|
|
|
// failing to returning a value as items are interned. But for typestate,
|
|
|
|
// where we first check a pred and then rely on it, ceasing to fail is ok.
|
2012-01-05 08:35:37 -06:00
|
|
|
pure fn get<T: copy>(itr: interner<T>, idx: uint) -> T {
|
2011-09-24 18:33:26 -05:00
|
|
|
unchecked {
|
2012-05-15 15:40:01 -05:00
|
|
|
itr.vect.get_elt(idx)
|
2011-09-24 18:33:26 -05:00
|
|
|
}
|
|
|
|
}
|
2011-08-04 12:46:10 -05:00
|
|
|
|
2012-05-15 15:40:01 -05:00
|
|
|
fn len<T>(itr: interner<T>) -> uint { ret itr.vect.len(); }
|