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

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

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

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

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

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

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

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

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

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

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

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