hashconsing icon indicating copy to clipboard operation
hashconsing copied to clipboard

`weak_table` optional dependency with adequate `WeakElement` implementation

Open AdrienChampion opened this issue 11 months ago • 2 comments

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.

AdrienChampion avatar Feb 26 '24 10:02 AdrienChampion

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?

asvarga avatar Feb 26 '24 15:02 asvarga

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.

AdrienChampion avatar Feb 27 '24 07:02 AdrienChampion