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
4
    pub(crate) const fn new() -> Self {
26
4
        InternCache {
27
4
            cache: OnceCell::new(),
28
4
        }
29
4
    }
30
}
31

            
32
impl<T: Eq + Hash + ?Sized> InternCache<T> {
33
    /// Helper: initialize the cache if needed, then lock it.
34
1195111
    fn cache(&self) -> MutexGuard<'_, WeakHashSet<Weak<T>>> {
35
1195111
        let cache = self.cache.get_or_init(|| Mutex::new(WeakHashSet::new()));
36
1195111
        cache.lock().expect("Poisoned lock lock for cache")
37
1195111
    }
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
1195103
    pub(crate) fn intern(&self, value: T) -> Arc<T> {
47
1195103
        let mut cache = self.cache();
48
1195103
        if let Some(pp) = cache.get(&value) {
49
1178805
            pp
50
        } else {
51
16298
            let arc = Arc::new(value);
52
16298
            cache.insert(Arc::clone(&arc));
53
16298
            arc
54
        }
55
1195103
    }
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
8
    pub(crate) fn intern_ref<'a, V>(&self, value: &'a V) -> Arc<T>
64
8
    where
65
8
        V: Hash + Eq + ?Sized,
66
8
        &'a V: Into<Arc<T>>,
67
8
        T: std::borrow::Borrow<V>,
68
8
    {
69
8
        let mut cache = self.cache();
70
8
        if let Some(arc) = cache.get(value) {
71
2
            arc
72
        } else {
73
6
            let arc = value.into();
74
6
            cache.insert(Arc::clone(&arc));
75
6
            arc
76
        }
77
8
    }
78
}
79

            
80
#[cfg(test)]
81
mod test {
82
    // @@ begin test lint list maintained by maint/add_warning @@
83
    #![allow(clippy::bool_assert_comparison)]
84
    #![allow(clippy::clone_on_copy)]
85
    #![allow(clippy::dbg_macro)]
86
    #![allow(clippy::mixed_attributes_style)]
87
    #![allow(clippy::print_stderr)]
88
    #![allow(clippy::print_stdout)]
89
    #![allow(clippy::single_char_pattern)]
90
    #![allow(clippy::unwrap_used)]
91
    #![allow(clippy::unchecked_duration_subtraction)]
92
    #![allow(clippy::useless_vec)]
93
    #![allow(clippy::needless_pass_by_value)]
94
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
95
    use super::*;
96

            
97
    #[test]
98
    fn interning_by_value() {
99
        // "intern" case.
100
        let c: InternCache<String> = InternCache::new();
101

            
102
        let s1 = c.intern("abc".to_string());
103
        let s2 = c.intern("def".to_string());
104
        let s3 = c.intern("abc".to_string());
105
        assert!(Arc::ptr_eq(&s1, &s3));
106
        assert!(!Arc::ptr_eq(&s1, &s2));
107
        assert_eq!(s2.as_ref(), "def");
108
        assert_eq!(s3.as_ref(), "abc");
109
    }
110

            
111
    #[test]
112
    fn interning_by_ref() {
113
        // "intern" case.
114
        let c: InternCache<str> = InternCache::new();
115

            
116
        let s1 = c.intern_ref("abc");
117
        let s2 = c.intern_ref("def");
118
        let s3 = c.intern_ref("abc");
119
        assert!(Arc::ptr_eq(&s1, &s3));
120
        assert!(!Arc::ptr_eq(&s1, &s2));
121
        assert_eq!(&*s2, "def");
122
        assert_eq!(&*s3, "abc");
123
    }
124
}