1
//! Declare types for interning various objects.
2

            
3
use once_cell::sync::OnceCell;
4
use std::hash::Hash;
5
use std::sync::{Arc, Mutex, MutexGuard, Weak};
6
use weak_table::WeakHashSet;
7

            
8
/// An InternCache is a lazily-constructed weak set of objects.
9
///
10
/// Let's break that down!  It's "lazily constructed" because it
11
/// doesn't actually allocate anything until you use it for the first
12
/// time.  That allows it to have a const [`new`](InternCache::new)
13
/// method, so you can make these static.
14
///
15
/// It's "weak" because it only holds weak references to its objects;
16
/// once every strong reference is gone, the object is unallocated.
17
/// Later, the hash entry is (lazily) removed.
18
pub(crate) struct InternCache<T: ?Sized> {
19
    /// Underlying hashset for interned objects
20
    cache: OnceCell<Mutex<WeakHashSet<Weak<T>>>>,
21
}
22

            
23
impl<T: ?Sized> InternCache<T> {
24
    /// Create a new, empty, InternCache.
25
    pub(crate) const fn new() -> Self {
26
        InternCache {
27
            cache: OnceCell::new(),
28
        }
29
    }
30
}
31

            
32
impl<T: Eq + Hash + ?Sized> InternCache<T> {
33
    /// Helper: initialize the cache if needed, then lock it.
34
75805
    fn cache(&self) -> MutexGuard<'_, WeakHashSet<Weak<T>>> {
35
75805
        let cache = self.cache.get_or_init(|| Mutex::new(WeakHashSet::new()));
36
75805
        cache.lock().expect("Poisoned lock lock for cache")
37
75805
    }
38
}
39

            
40
impl<T: Eq + Hash> InternCache<T> {
41
    /// Intern a given value into this cache.
42
    ///
43
    /// If `value` is already stored in this cache, we return a
44
    /// reference to the stored value.  Otherwise, we insert `value`
45
    /// into the cache, and return that.
46
75804
    pub(crate) fn intern(&self, value: T) -> Arc<T> {
47
75804
        let mut cache = self.cache();
48
75804
        if let Some(pp) = cache.get(&value) {
49
75507
            pp
50
        } else {
51
297
            let arc = Arc::new(value);
52
297
            cache.insert(Arc::clone(&arc));
53
297
            arc
54
        }
55
75804
    }
56
}
57

            
58
impl<T: Hash + Eq + ?Sized> InternCache<T> {
59
    /// Intern an object by reference.
60
    ///
61
    /// Works with unsized types, but requires that the reference implements
62
    /// `Into<Arc<T>>`.
63
1
    pub(crate) fn intern_ref<'a, V>(&self, value: &'a V) -> Arc<T>
64
1
    where
65
1
        V: Hash + Eq + ?Sized,
66
1
        &'a V: Into<Arc<T>>,
67
1
        T: std::borrow::Borrow<V>,
68
1
    {
69
1
        let mut cache = self.cache();
70
1
        if let Some(arc) = cache.get(value) {
71
            arc
72
        } else {
73
1
            let arc = value.into();
74
1
            cache.insert(Arc::clone(&arc));
75
1
            arc
76
        }
77
1
    }
78
}