cl_structures/intern.rs
1//! Interners for [strings](string_interner) and arbitrary [types](typed_interner).
2//!
3//! An object is [Interned][1] if it is allocated within one of the interners
4//! in this module. [Interned][1] values have referential equality semantics, and
5//! [Deref](std::ops::Deref) to the value within their respective intern pool.
6//!
7//! This means, of course, that the same value interned in two different pools will be
8//! considered *not equal* by [Eq] and [Hash](std::hash::Hash).
9//!
10//! [1]: interned::Interned
11
12pub mod interned {
13 //! An [Interned] reference asserts its wrapped value has referential equality.
14 use super::string_interner::StringInterner;
15 use std::{
16 fmt::{Debug, Display},
17 hash::Hash,
18 ops::Deref,
19 };
20
21 /// An [Interned] value is one that is *referentially comparable*.
22 /// That is, the interned value is unique in memory, simplifying
23 /// its equality and hashing implementation.
24 ///
25 /// Comparing [Interned] values via [PartialOrd] or [Ord] will still
26 /// dereference to the wrapped pointers, and as such, may produce
27 /// results inconsistent with [PartialEq] or [Eq].
28 #[repr(transparent)]
29 pub struct Interned<'a, T: ?Sized> {
30 value: &'a T,
31 }
32
33 impl<'a, T: ?Sized> Interned<'a, T> {
34 /// Gets the internal value as a pointer
35 pub fn as_ptr(interned: &Self) -> *const T {
36 interned.value
37 }
38
39 /// Gets the internal value as a reference with the interner's lifetime
40 pub fn to_ref(&self) -> &'a T {
41 self.value
42 }
43 }
44
45 impl<T: ?Sized + Debug> Debug for Interned<'_, T> {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 write!(f, "~")?;
48 self.value.fmt(f)
49 }
50 }
51 impl<'a, T: ?Sized> Interned<'a, T> {
52 pub(super) fn new(value: &'a T) -> Self {
53 Self { value }
54 }
55 }
56 impl<T: ?Sized> Deref for Interned<'_, T> {
57 type Target = T;
58 fn deref(&self) -> &Self::Target {
59 self.value
60 }
61 }
62 impl<T: ?Sized> Copy for Interned<'_, T> {}
63 impl<T: ?Sized> Clone for Interned<'_, T> {
64 fn clone(&self) -> Self {
65 *self
66 }
67 }
68 // TODO: These implementations are subtly incorrect, as they do not line up with `eq`
69 // impl<'a, T: ?Sized + PartialOrd> PartialOrd for Interned<'a, T> {
70 // fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
71 // match self == other {
72 // true => Some(std::cmp::Ordering::Equal),
73 // false => self.value.partial_cmp(other.value),
74 // }
75 // }
76 // }
77 // impl<'a, T: ?Sized + Ord> Ord for Interned<'a, T> {
78 // fn cmp(&self, other: &Self) -> std::cmp::Ordering {
79 // match self == other {
80 // true => std::cmp::Ordering::Equal,
81 // false => self.value.cmp(other.value),
82 // }
83 // }
84 // }
85
86 impl<T: ?Sized> Eq for Interned<'_, T> {}
87 impl<T: ?Sized> PartialEq for Interned<'_, T> {
88 fn eq(&self, other: &Self) -> bool {
89 std::ptr::eq(self.value, other.value)
90 }
91 }
92 impl<T: ?Sized> Hash for Interned<'_, T> {
93 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
94 Self::as_ptr(self).hash(state)
95 }
96 }
97 impl<T: ?Sized + Display> Display for Interned<'_, T> {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 self.value.fmt(f)
100 }
101 }
102
103 impl<T: AsRef<str>> From<T> for Interned<'static, str> {
104 /// Types which implement [`AsRef<str>`] will be stored in the global [StringInterner]
105 fn from(value: T) -> Self {
106 from_str(value.as_ref())
107 }
108 }
109 fn from_str(value: &str) -> Interned<'static, str> {
110 let global_interner = StringInterner::global();
111 global_interner.get_or_insert(value)
112 }
113}
114
115pub mod string_interner {
116 //! A [StringInterner] hands out [Interned] copies of each unique string given to it.
117
118 use super::interned::Interned;
119 use cl_arena::dropless_arena::DroplessArena;
120 use std::{
121 collections::HashSet,
122 sync::{OnceLock, RwLock},
123 };
124
125 /// A string interner hands out [Interned] copies of each unique string given to it.
126 #[derive(Default)]
127 pub struct StringInterner<'a> {
128 arena: DroplessArena<'a>,
129 keys: RwLock<HashSet<&'a str>>,
130 }
131
132 impl StringInterner<'static> {
133 /// Gets a reference to a global string interner whose [Interned] strings are `'static`
134 pub fn global() -> &'static Self {
135 static GLOBAL_INTERNER: OnceLock<StringInterner<'static>> = OnceLock::new();
136
137 // SAFETY: The RwLock within the interner's `keys` protects the arena
138 // from being modified concurrently.
139 GLOBAL_INTERNER.get_or_init(|| StringInterner {
140 arena: DroplessArena::new(),
141 keys: Default::default(),
142 })
143 }
144 }
145
146 impl<'a> StringInterner<'a> {
147 /// Creates a new [StringInterner] backed by the provided [DroplessArena]
148 pub fn new(arena: DroplessArena<'a>) -> Self {
149 Self { arena, keys: RwLock::new(HashSet::new()) }
150 }
151
152 /// Returns an [Interned] copy of the given string,
153 /// allocating a new one if it doesn't already exist.
154 ///
155 /// # Blocks
156 /// This function blocks when the interner is held by another thread.
157 pub fn get_or_insert(&'a self, value: &str) -> Interned<'a, str> {
158 let Self { arena, keys } = self;
159
160 // Safety: Holding this write guard for the entire duration of this
161 // function enforces a safety invariant. See StringInterner::global.
162 let mut keys = keys.write().expect("should not be poisoned");
163
164 Interned::new(match keys.get(value) {
165 Some(value) => value,
166 None => {
167 let value = match value {
168 "" => "", // Arena will panic if passed an empty string
169 _ => arena.alloc_str(value),
170 };
171 keys.insert(value);
172 value
173 }
174 })
175 }
176 /// Gets a reference to the interned copy of the given value, if it exists
177 /// # Blocks
178 /// This function blocks when the interner is held by another thread.
179 pub fn get(&'a self, value: &str) -> Option<Interned<'a, str>> {
180 let keys = self.keys.read().expect("should not be poisoned");
181 keys.get(value).copied().map(Interned::new)
182 }
183 }
184
185 impl std::fmt::Debug for StringInterner<'_> {
186 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187 f.debug_struct("Interner")
188 .field("keys", &self.keys)
189 .finish()
190 }
191 }
192
193 impl std::fmt::Display for StringInterner<'_> {
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 let Ok(keys) = self.keys.read() else {
196 return write!(f, "Could not lock StringInterner key map.");
197 };
198 let mut keys: Vec<_> = keys.iter().collect();
199 keys.sort();
200
201 writeln!(f, "Keys:")?;
202 for (idx, key) in keys.iter().enumerate() {
203 writeln!(f, "{idx}:\t\"{key}\"")?
204 }
205 writeln!(f, "Count: {}", keys.len())?;
206
207 Ok(())
208 }
209 }
210
211 // # Safety:
212 // This is fine because StringInterner::get_or_insert(v) holds a RwLock
213 // for its entire duration, and doesn't touch the non-(Send+Sync) arena
214 // unless the lock is held by a write guard.
215 unsafe impl Send for StringInterner<'_> {}
216 unsafe impl Sync for StringInterner<'_> {}
217
218 #[cfg(test)]
219 mod tests {
220 use super::StringInterner;
221
222 macro_rules! ptr_eq {
223 ($a: expr, $b: expr $(, $($t:tt)*)?) => {
224 assert_eq!(std::ptr::addr_of!($a), std::ptr::addr_of!($b) $(, $($t)*)?)
225 };
226 }
227 macro_rules! ptr_ne {
228 ($a: expr, $b: expr $(, $($t:tt)*)?) => {
229 assert_ne!(std::ptr::addr_of!($a), std::ptr::addr_of!($b) $(, $($t)*)?)
230 };
231 }
232
233 #[test]
234 fn empties_is_unique() {
235 let interner = StringInterner::global();
236 let empty = interner.get_or_insert("");
237 let empty2 = interner.get_or_insert("");
238 ptr_eq!(*empty, *empty2);
239 }
240 #[test]
241 fn non_empty_is_unique() {
242 let interner = StringInterner::global();
243 let nonempty1 = interner.get_or_insert("not empty!");
244 let nonempty2 = interner.get_or_insert("not empty!");
245 let different = interner.get_or_insert("different!");
246 ptr_eq!(*nonempty1, *nonempty2);
247 ptr_ne!(*nonempty1, *different);
248 }
249 }
250}
251
252pub mod typed_interner {
253 //! A [TypedInterner] hands out [Interned] references for arbitrary types.
254 //!
255 //! Note: It is a *logic error* to modify the returned reference via interior mutability
256 //! in a way that changes the values produced by [Eq] and [Hash].
257 //!
258 //! See the standard library [HashSet] for more details.
259 use super::interned::Interned;
260 use cl_arena::typed_arena::TypedArena;
261 use std::{collections::HashSet, hash::Hash, sync::RwLock};
262
263 /// A [TypedInterner] hands out [Interned] references for arbitrary types.
264 ///
265 /// See the [module-level documentation](self) for more information.
266 pub struct TypedInterner<'a, T: Eq + Hash> {
267 arena: TypedArena<'a, T>,
268 keys: RwLock<HashSet<&'a T>>,
269 }
270
271 impl<'a, T: Eq + Hash> Default for TypedInterner<'a, T> {
272 fn default() -> Self {
273 Self { arena: Default::default(), keys: Default::default() }
274 }
275 }
276
277 impl<'a, T: Eq + Hash> TypedInterner<'a, T> {
278 /// Creates a new [TypedInterner] backed by the provided [TypedArena]
279 pub fn new(arena: TypedArena<'a, T>) -> Self {
280 Self { arena, keys: RwLock::new(HashSet::new()) }
281 }
282
283 /// Converts the given value into an [Interned] value.
284 ///
285 /// # Blocks
286 /// This function blocks when the interner is held by another thread.
287 pub fn get_or_insert(&'a self, value: T) -> Interned<'a, T> {
288 let Self { arena, keys } = self;
289
290 // Safety: Locking the keyset for the entire duration of this function
291 // enforces a safety invariant when the interner is stored in a global.
292 let mut keys = keys.write().expect("should not be poisoned");
293
294 Interned::new(match keys.get(&value) {
295 Some(value) => value,
296 None => {
297 let value = arena.alloc(value);
298 keys.insert(value);
299 value
300 }
301 })
302 }
303 /// Returns the [Interned] copy of the given value, if one already exists
304 ///
305 /// # Blocks
306 /// This function blocks when the interner is being written to by another thread.
307 pub fn get(&self, value: &T) -> Option<Interned<'a, T>> {
308 let keys = self.keys.read().expect("should not be poisoned");
309 keys.get(value).copied().map(Interned::new)
310 }
311 }
312
313 /// # Safety
314 /// This should be safe because references yielded by
315 /// [get_or_insert](TypedInterner::get_or_insert) are unique, and the function uses
316 /// the [RwLock] around the [HashSet] to ensure mutual exclusion
317 unsafe impl<'a, T: Eq + Hash + Send> Send for TypedInterner<'a, T> where &'a T: Send {}
318 unsafe impl<T: Eq + Hash + Send + Sync> Sync for TypedInterner<'_, T> {}
319}