tor_basic_utils/intern.rs
1//! Declare types for interning various objects.
2
3use std::fmt::Debug;
4use std::hash::Hash;
5use std::sync::{Arc, Mutex, MutexGuard, OnceLock, Weak};
6
7use derive_deftly::define_derive_deftly;
8use derive_more::{Deref, Display, Into};
9use 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.
14type 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)]
35pub struct Intern<T: ?Sized>(Arc<T>);
36
37impl<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>.
49impl<'a, T: ?Sized> From<&'a Intern<T>> for &'a Arc<T> {
50 fn from(value: &'a Intern<T>) -> Self {
51 &value.0
52 }
53}
54
55/// Offers access to globally available cache for [`InternCache`].
56///
57/// Typically derived using [`crate::derive_deftly_template_GloballyInternable`].
58pub 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 fn into_intern(self) -> Intern<Self>
69 where
70 Self: Eq + Hash + 'static,
71 {
72 Self::intern_cache().intern(self)
73 }
74}
75
76define_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 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.
101pub 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
108impl<T: ?Sized> InternCache<T> {
109 /// Create a new, empty, InternCache.
110 pub const fn new() -> Self {
111 InternCache {
112 cache: OnceLock::new(),
113 }
114 }
115}
116
117impl<T: ?Sized> Default for InternCache<T> {
118 fn default() -> Self {
119 Self::new()
120 }
121}
122
123impl<T: Eq + Hash + ?Sized> InternCache<T> {
124 /// Helper: initialize the cache if needed, then lock it.
125 fn cache(&self) -> MutexGuard<'_, WeakHashSet<Weak<T>>> {
126 let cache = self.cache.get_or_init(|| Mutex::new(WeakHashSet::new()));
127 cache.lock().expect("Poisoned lock lock for cache")
128 }
129}
130
131impl<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 pub fn intern(&self, value: T) -> Intern<T> {
138 let mut cache = self.cache();
139 if let Some(pp) = cache.get(&value) {
140 Intern(pp)
141 } else {
142 let arc = Arc::new(value);
143 cache.insert(Arc::clone(&arc));
144 Intern(arc)
145 }
146 }
147}
148
149impl<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 pub fn intern_ref<'a, V>(&self, value: &'a V) -> Intern<T>
155 where
156 V: Hash + Eq + ?Sized,
157 &'a V: Into<Arc<T>>,
158 T: std::borrow::Borrow<V>,
159 {
160 let mut cache = self.cache();
161 if let Some(arc) = cache.get(value) {
162 Intern(arc)
163 } else {
164 let arc = value.into();
165 cache.insert(Arc::clone(&arc));
166 Intern(arc)
167 }
168 }
169}
170
171#[cfg(test)]
172mod 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}