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

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

            
7
use derive_deftly::define_derive_deftly;
8
use derive_more::{Deref, Display, Into};
9
use educe::Educe;
10

            
11
/// Alias to force use of RandomState, regardless of features enabled in `weak_tables`.
12
///
13
/// See <https://github.com/tov/weak-table-rs/issues/23> for discussion.
14
type WeakHashSet<T> = weak_table::WeakHashSet<T, std::hash::RandomState>;
15

            
16
/// A wrapper around [`Arc`] representing owned [`InternCache`] entries.
17
///
18
/// The wrapper type serves the purpose of semantic meaning only, implying that
19
/// this value is cached in some way or another by this module.
20
///
21
/// We only conveniently allow obtaining the underlying [`Arc`] with a [`From`] but not the
22
/// other way around.  This means that interfacing code can make the type to
23
/// "forget" it originated from an [`InternCache`] but not the other way around,
24
/// i.e. cannot accidentally create fake entries that look like they came from an
25
/// [`InternCache`].  If one really has to circumvent this, then the
26
/// [`Intern::new_uncached_uninterned()`] method exists.
27
///
28
/// This ensures that interning is done everywhere that it's expected,
29
/// avoiding excess memory usage.
30
//
31
// Right now, this is the bare minimum of derives; it may need more in the
32
// future.  If so, just add them.
33
#[derive(Debug, Default, PartialEq, Eq, Hash, Display, Into, Deref, Educe)]
34
#[educe(Clone)]
35
pub struct Intern<T: ?Sized>(Arc<T>);
36

            
37
impl<T: ?Sized> Intern<T> {
38
    /// Creates an [`Intern`] from an arbitrary [`Arc`].
39
    ///
40
    /// The use of this is generally discouraged, as it effectively destroys
41
    /// the boundary of implying that certain cache entries come from the
42
    /// [`InternCache`].
43
    pub fn new_uncached_uninterned(value: Arc<T>) -> Intern<T> {
44
        Intern(value)
45
    }
46
}
47

            
48
// Some Arti code is pretty keen on using &Arc<T>.
49
impl<'a, T: ?Sized> From<&'a Intern<T>> for &'a Arc<T> {
50
18338790
    fn from(value: &'a Intern<T>) -> Self {
51
18338790
        &value.0
52
18338790
    }
53
}
54

            
55
/// Offers access to globally available cache for [`InternCache`].
56
///
57
/// Typically derived using [`crate::derive_deftly_template_GloballyInternable`].
58
pub trait GloballyInternable: Sized {
59
    /// Returns a reference to the global cache instance of this type.
60
    ///
61
    /// Implemented by implementors of this trait.
62
    /// Users of the trait should usually use [`GloballyInternable::into_intern()`].
63
    fn intern_cache() -> &'static InternCache<Self>;
64

            
65
    /// Places `self` into the global cache.
66
    ///
67
    /// Please use this instead of `T::intern_cache().intern(value)`.
68
2165895
    fn into_intern(self) -> Intern<Self>
69
2165895
    where
70
2165895
        Self: Eq + Hash + 'static,
71
    {
72
2165895
        Self::intern_cache().intern(self)
73
2165895
    }
74
}
75

            
76
define_derive_deftly! {
77
    /// Implement the [`GloballyInternable`] trait for a specific type.
78
    ///
79
    /// The implementation in itself is trivial and straightforward with this
80
    /// macro primarily serving as a convenience method.
81
    export GloballyInternable for struct:
82

            
83
    impl $crate::intern::GloballyInternable for $ttype {
84
2165895
        fn intern_cache() -> &'static $crate::intern::InternCache<Self> {
85
            static S: $crate::intern::InternCache::<$ttype> = $crate::intern::InternCache::new();
86
            &S
87
        }
88
    }
89
}
90

            
91
/// An InternCache is a lazily-constructed weak set of objects.
92
///
93
/// Let's break that down!  It's "lazily constructed" because it
94
/// doesn't actually allocate anything until you use it for the first
95
/// time.  That allows it to have a const [`new`](InternCache::new)
96
/// method, so you can make these static.
97
///
98
/// It's "weak" because it only holds weak references to its objects;
99
/// once every strong reference is gone, the object is unallocated.
100
/// Later, the hash entry is (lazily) removed.
101
pub struct InternCache<T: ?Sized> {
102
    /// Underlying hashset for interned objects
103
    //
104
    // TODO: If WeakHashSet::new is someday const, we can do away with OnceLock here.
105
    cache: OnceLock<Mutex<WeakHashSet<Weak<T>>>>,
106
}
107

            
108
impl<T: ?Sized> InternCache<T> {
109
    /// Create a new, empty, InternCache.
110
4
    pub const fn new() -> Self {
111
4
        InternCache {
112
4
            cache: OnceLock::new(),
113
4
        }
114
4
    }
115
}
116

            
117
impl<T: ?Sized> Default for InternCache<T> {
118
    fn default() -> Self {
119
        Self::new()
120
    }
121
}
122

            
123
impl<T: Eq + Hash + ?Sized> InternCache<T> {
124
    /// Helper: initialize the cache if needed, then lock it.
125
2165911
    fn cache(&self) -> MutexGuard<'_, WeakHashSet<Weak<T>>> {
126
2165911
        let cache = self.cache.get_or_init(|| Mutex::new(WeakHashSet::new()));
127
2165911
        cache.lock().expect("Poisoned lock lock for cache")
128
2165911
    }
129
}
130

            
131
impl<T: Eq + Hash> InternCache<T> {
132
    /// Intern a given value into this cache.
133
    ///
134
    /// If `value` is already stored in this cache, we return a
135
    /// reference to the stored value.  Otherwise, we insert `value`
136
    /// into the cache, and return that.
137
2165901
    pub fn intern(&self, value: T) -> Intern<T> {
138
2165901
        let mut cache = self.cache();
139
2165901
        if let Some(pp) = cache.get(&value) {
140
2057242
            Intern(pp)
141
        } else {
142
108659
            let arc = Arc::new(value);
143
108659
            cache.insert(Arc::clone(&arc));
144
108659
            Intern(arc)
145
        }
146
2165901
    }
147
}
148

            
149
impl<T: Hash + Eq + ?Sized> InternCache<T> {
150
    /// Intern an object by reference.
151
    ///
152
    /// Works with unsized types, but requires that the reference implements
153
    /// `Into<Arc<T>>`.
154
10
    pub fn intern_ref<'a, V>(&self, value: &'a V) -> Intern<T>
155
10
    where
156
10
        V: Hash + Eq + ?Sized,
157
10
        &'a V: Into<Arc<T>>,
158
10
        T: std::borrow::Borrow<V>,
159
    {
160
10
        let mut cache = self.cache();
161
10
        if let Some(arc) = cache.get(value) {
162
4
            Intern(arc)
163
        } else {
164
6
            let arc = value.into();
165
6
            cache.insert(Arc::clone(&arc));
166
6
            Intern(arc)
167
        }
168
10
    }
169
}
170

            
171
#[cfg(test)]
172
mod test {
173
    // @@ begin test lint list maintained by maint/add_warning @@
174
    #![allow(clippy::bool_assert_comparison)]
175
    #![allow(clippy::clone_on_copy)]
176
    #![allow(clippy::dbg_macro)]
177
    #![allow(clippy::mixed_attributes_style)]
178
    #![allow(clippy::print_stderr)]
179
    #![allow(clippy::print_stdout)]
180
    #![allow(clippy::single_char_pattern)]
181
    #![allow(clippy::unwrap_used)]
182
    #![allow(clippy::unchecked_time_subtraction)]
183
    #![allow(clippy::useless_vec)]
184
    #![allow(clippy::needless_pass_by_value)]
185
    #![allow(clippy::string_slice)] // See arti#2571
186
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
187
    use super::*;
188

            
189
    #[test]
190
    fn interning_by_value() {
191
        // "intern" case.
192
        let c: InternCache<String> = InternCache::new();
193

            
194
        let s1: Arc<String> = c.intern("abc".to_string()).into();
195
        let s2 = c.intern("def".to_string()).into();
196
        let s3 = c.intern("abc".to_string()).into();
197
        assert!(Arc::ptr_eq(&s1, &s3));
198
        assert!(!Arc::ptr_eq(&s1, &s2));
199
        assert_eq!(s2.as_ref(), "def");
200
        assert_eq!(s3.as_ref(), "abc");
201
    }
202

            
203
    #[test]
204
    fn interning_by_ref() {
205
        // "intern" case.
206
        let c: InternCache<str> = InternCache::new();
207

            
208
        let s1: Arc<str> = c.intern_ref("abc").into();
209
        let s2 = c.intern_ref("def").into();
210
        let s3 = c.intern_ref("abc").into();
211
        assert!(Arc::ptr_eq(&s1, &s3));
212
        assert!(!Arc::ptr_eq(&s1, &s2));
213
        assert_eq!(&*s2, "def");
214
        assert_eq!(&*s3, "abc");
215
    }
216
}