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-08-15 18:38:23 -05:00
|
|
|
import std::vec;
|
2011-07-05 04:48:19 -05:00
|
|
|
import std::map;
|
|
|
|
import std::map::hashmap;
|
|
|
|
import std::map::hashfn;
|
|
|
|
import std::map::eqfn;
|
|
|
|
import std::option;
|
|
|
|
import std::option::none;
|
|
|
|
import std::option::some;
|
|
|
|
|
2011-08-12 08:36:51 -05:00
|
|
|
type interner<T> =
|
2011-08-12 09:15:18 -05:00
|
|
|
{map: hashmap<T, uint>,
|
2011-08-04 18:20:09 -05:00
|
|
|
mutable vect: [T],
|
2011-08-12 09:15:18 -05:00
|
|
|
hasher: hashfn<T>,
|
|
|
|
eqer: eqfn<T>};
|
2011-07-05 04:48:19 -05:00
|
|
|
|
2011-08-12 08:36:51 -05:00
|
|
|
fn mk<@T>(hasher: hashfn<T>, eqer: eqfn<T>) -> interner<T> {
|
2011-08-13 02:09:25 -05:00
|
|
|
let m = map::mk_hashmap::<T, uint>(hasher, eqer);
|
2011-08-19 17:16:48 -05:00
|
|
|
ret {map: m, mutable vect: [], hasher: hasher, eqer: eqer};
|
2011-07-05 04:48:19 -05:00
|
|
|
}
|
2011-08-04 12:46:10 -05:00
|
|
|
|
2011-08-12 08:36:51 -05:00
|
|
|
fn intern<@T>(itr: &interner<T>, val: &T) -> uint {
|
2011-07-27 07:19:39 -05:00
|
|
|
alt itr.map.find(val) {
|
|
|
|
some(idx) { ret idx; }
|
|
|
|
none. {
|
2011-08-13 02:09:25 -05:00
|
|
|
let new_idx = vec::len::<T>(itr.vect);
|
2011-07-27 07:19:39 -05:00
|
|
|
itr.map.insert(val, new_idx);
|
2011-08-19 17:16:48 -05:00
|
|
|
itr.vect += [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-08-19 17:16:48 -05:00
|
|
|
fn get<T>(itr: &interner<T>, idx: uint) -> T { ret itr.vect[idx]; }
|
2011-07-01 18:59:03 -05:00
|
|
|
|
2011-08-19 17:16:48 -05:00
|
|
|
fn len<T>(itr: &interner<T>) -> uint { ret vec::len(itr.vect); }
|
2011-08-04 12:46:10 -05:00
|
|
|
|