rust/src/rustc/syntax/util/interner.rs

40 lines
1.2 KiB
Rust
Raw Normal View History

// 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.
import std::map;
2011-09-12 18:13:28 -05:00
import std::map::{hashmap, hashfn, eqfn};
type interner<T> =
{map: hashmap<T, uint>,
mutable vect: [T],
hasher: hashfn<T>,
eqer: eqfn<T>};
fn mk<T: copy>(hasher: hashfn<T>, eqer: eqfn<T>) -> interner<T> {
2012-03-12 17:52:30 -05:00
let m = map::new_hashmap::<T, uint>(hasher, eqer);
ret {map: m, mutable vect: [], hasher: hasher, eqer: eqer};
}
2011-08-04 12:46:10 -05: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; }
none {
let new_idx = vec::len::<T>(itr.vect);
2011-07-27 07:19:39 -05:00
itr.map.insert(val, new_idx);
itr.vect += [val];
2011-07-27 07:19:39 -05:00
ret new_idx;
}
}
}
2011-08-04 12:46:10 -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.
pure fn get<T: copy>(itr: interner<T>, idx: uint) -> T {
unchecked {
itr.vect[idx]
}
}
2011-08-04 12:46:10 -05:00
fn len<T>(itr: interner<T>) -> uint { ret vec::len(itr.vect); }