2011-07-05 11:48:19 +02: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-11-11 00:41:42 +08:00
|
|
|
import std::{vec, map};
|
2011-09-12 16:13:28 -07:00
|
|
|
import std::map::{hashmap, hashfn, eqfn};
|
|
|
|
import std::option::{none, some};
|
2011-07-05 11:48:19 +02:00
|
|
|
|
2011-08-12 06:36:51 -07:00
|
|
|
type interner<T> =
|
2011-08-12 07:15:18 -07:00
|
|
|
{map: hashmap<T, uint>,
|
2011-08-04 16:20:09 -07:00
|
|
|
mutable vect: [T],
|
2011-08-12 07:15:18 -07:00
|
|
|
hasher: hashfn<T>,
|
|
|
|
eqer: eqfn<T>};
|
2011-07-05 11:48:19 +02:00
|
|
|
|
2011-10-25 15:56:55 +02:00
|
|
|
fn mk<T>(hasher: hashfn<T>, eqer: eqfn<T>) -> interner<T> {
|
2011-08-13 00:09:25 -07:00
|
|
|
let m = map::mk_hashmap::<T, uint>(hasher, eqer);
|
2011-08-19 15:16:48 -07:00
|
|
|
ret {map: m, mutable vect: [], hasher: hasher, eqer: eqer};
|
2011-07-05 11:48:19 +02:00
|
|
|
}
|
2011-08-04 10:46:10 -07:00
|
|
|
|
2011-10-25 15:56:55 +02:00
|
|
|
fn intern<T>(itr: interner<T>, val: T) -> uint {
|
2011-07-27 14:19:39 +02:00
|
|
|
alt itr.map.find(val) {
|
|
|
|
some(idx) { ret idx; }
|
|
|
|
none. {
|
2011-08-13 00:09:25 -07:00
|
|
|
let new_idx = vec::len::<T>(itr.vect);
|
2011-07-27 14:19:39 +02:00
|
|
|
itr.map.insert(val, new_idx);
|
2011-08-19 15:16:48 -07:00
|
|
|
itr.vect += [val];
|
2011-07-27 14:19:39 +02:00
|
|
|
ret new_idx;
|
|
|
|
}
|
2011-07-05 11:48:19 +02:00
|
|
|
}
|
|
|
|
}
|
2011-08-04 10:46:10 -07:00
|
|
|
|
2011-09-24 16:33:26 -07: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.
|
2011-10-25 15:56:55 +02:00
|
|
|
pure fn get<T>(itr: interner<T>, idx: uint) -> T {
|
2011-09-24 16:33:26 -07:00
|
|
|
unchecked {
|
|
|
|
itr.vect[idx]
|
|
|
|
}
|
|
|
|
}
|
2011-08-04 10:46:10 -07:00
|
|
|
|
2011-09-24 16:33:26 -07:00
|
|
|
fn len<T>(itr: interner<T>) -> uint { ret vec::len(itr.vect); }
|