hashconsing
hashconsing copied to clipboard
`weak_table` optional dependency with adequate `WeakElement` implementation
We prefer not adding dependencies if we can avoid it, but at least two users expressed interest in integrating with weak_table
(#15). While there is a reasonable workaround, actual integration would be much nicer.
This issue is to assess how big the interest for integration is, please let us know here.
My use case for this was for memoizing a function that takes an HConsed<T>
with a WeakKeyHashMap
so the table itself wouldn't contribute to the HConsed<T>::elm
's reference count. I'm doing something like:
use once_cell::sync::Lazy;
use std::sync::{RwLock, Weak};
use weak_table::WeakKeyHashMap;
pub fn term_to_output(term: &Term) -> Output {
static MEMO: Lazy<RwLock<WeakKeyHashMap<Weak<ActualTerm>, Output>>> =
Lazy::new(|| RwLock::new(WeakKeyHashMap::default()));
if let Some(ret) = MEMO.read().unwrap().get(&term.0) {
return *ret;
}
let ret: Output = todo!();
MEMO.write().unwrap().insert(term.0.to_weak_ref().upgrade().unwrap(), ret); // yuck
ret
}
Questions:
- Is there a better way to accomplish this with what
hashconsing
already provides? - Can this optional dependency also provide integration with https://crates.io/crates/memoize via weak versions of the structures in
hashconsing::hash_coll
?
Regarding caching using weak references, I actually wrote an example in a branch back when I misunderstood your question in #15. It only uses std.