bumpalo_intern/direct.rs
1//! Defines intern utility providing direct `&str` wrapped interning.
2//!
3//! Here is the basic usage of the [`DirectInternStore`].
4//!
5//! ```
6//! use bumpalo_intern::direct::{InternedStr, FromInterned, DirectInternStore};
7//!
8//! // You should have a simple &str wrapper.
9//! #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
10//! struct MyInterned<'a>(InternedStr<'a>);
11//!
12//! // And the type must implement FromInterned.
13//! impl<'arena> FromInterned<'arena> for MyInterned<'arena> {
14//! fn from_interned(v: InternedStr<'arena>) -> Self {
15//! Self(v)
16//! }
17//!
18//! fn as_interned(&self) -> InternedStr<'arena> {
19//! self.0
20//! }
21//! }
22//!
23//! let arena = bumpalo::Bump::new();
24//! let mut interner = DirectInternStore::new(&arena);
25//!
26//! let foo: MyInterned<'_> = interner.ensure(&"foo".to_string());
27//! let foo2 = interner.ensure(&"foo".to_string());
28//! let bar = interner.ensure(&"bar".to_string());
29//!
30//! assert_eq!(foo, foo2);
31//! assert_ne!(foo, bar);
32//! assert_eq!(foo.as_interned().as_str(), "foo");
33//! assert_eq!(bar.as_interned().as_str(), "bar");
34//! ```
35//!
36
37use std::{collections::HashMap, fmt::Debug, hash::Hash, iter::FusedIterator, marker::PhantomData};
38
39use bumpalo::Bump;
40
41/// Wrapped `&str` interned by [`DirectInternStore`].
42///
43/// Equality and hashing are based on pointer identity (see the `PartialEq`
44/// impl below), not string content, so two separately-interned copies of
45/// the same text compare unequal:
46///
47/// ```
48#[doc = doctest_file::include_doctest!("src/doctests/direct_myinterned.rs", hidden)]
49/// use bumpalo_intern::direct::DirectInternStore;
50///
51/// let arena1 = bumpalo::Bump::new();
52/// let mut store1 = DirectInternStore::new(&arena1);
53/// let foo1: MyInterned<'_> = store1.ensure("foo");
54///
55/// let arena2 = bumpalo::Bump::new();
56/// let mut store2 = DirectInternStore::new(&arena2);
57/// let foo2: MyInterned<'_> = store2.ensure("foo");
58///
59/// // Separately-interned copies of the same text are NOT equal...
60/// assert_ne!(foo1.0, foo2.0);
61/// // ...even though their content is identical.
62/// assert_eq!(foo1.0.as_str(), foo2.0.as_str());
63///
64/// // A `Copy` of the same InternedStr, however, is equal.
65/// let foo1_copy = foo1;
66/// assert_eq!(foo1.0, foo1_copy.0);
67/// ```
68#[derive(Eq, Clone, Copy)]
69pub struct InternedStr<'arena>(&'arena str);
70
71impl<'arena> InternedStr<'arena> {
72 pub fn as_str(&self) -> &'arena str {
73 self.0
74 }
75}
76
77impl Debug for InternedStr<'_> {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 f.debug_tuple("InternedStr")
80 .field(&std::ptr::from_ref(self.0))
81 .field(&self.0)
82 .finish()
83 }
84}
85
86/// InternedStr equality is computed on the pointer, as it's interned and must have the same pointer
87/// as long as the content is the same.
88impl PartialEq for InternedStr<'_> {
89 fn eq(&self, other: &Self) -> bool {
90 std::ptr::eq(self.0, other.0)
91 }
92}
93
94/// Hash is based on the pointer, as it's interned.
95impl Hash for InternedStr<'_> {
96 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
97 std::ptr::hash(self.0, state)
98 }
99}
100
101/// Trait that the actual Interned object must implements.
102pub trait FromInterned<'arena>: Copy {
103 fn from_interned(v: InternedStr<'arena>) -> Self;
104
105 fn as_interned(&self) -> InternedStr<'arena>;
106}
107
108/// Stored value in [`DirectInternStore`].
109#[derive(Debug, PartialEq, Eq)]
110pub enum StoredValue<'arena, T> {
111 Canonical(T),
112 Alias { alias: &'arena str, canonical: T },
113}
114
115impl<T: Copy> StoredValue<'_, T> {
116 fn as_canonical(&self) -> T {
117 match self {
118 StoredValue::Canonical(x) => *x,
119 StoredValue::Alias { canonical, .. } => *canonical,
120 }
121 }
122}
123
124/// Error returned when try_insert* method fails.
125#[derive(Debug, PartialEq, Eq)]
126pub struct OccupiedError<'arena, T> {
127 pub existing: StoredValue<'arena, T>,
128}
129
130/// Manages interned `&str` in the arena allocator.
131/// This can also handles alias.
132/// Semantics of alias:
133/// * Alias behaves as the same as canonical.
134/// One can call [`ensure`] for the alias, and the corresponding canonical value is returned.
135/// * Once registered, it's impossible to change the value pointing the alias.
136/// Caller can't register alias which is already registered as canonical,
137/// or vice versa.
138pub struct DirectInternStore<'arena, T> {
139 // Contains None for canonical, Some for alias.
140 records: HashMap<&'arena str, Option<InternedStr<'arena>>>,
141 allocator: &'arena Bump,
142 phantom: PhantomData<T>,
143}
144
145impl<'arena, T> DirectInternStore<'arena, T> {
146 /// Creates a new instance.
147 pub fn new(allocator: &'arena Bump) -> Self {
148 Self {
149 records: HashMap::new(),
150 allocator,
151 phantom: PhantomData,
152 }
153 }
154}
155
156impl<'arena, T: FromInterned<'arena>> DirectInternStore<'arena, T> {
157 /// Interns the given `str` and returns the shared instance.
158 /// If `value` is registered as alias, it'll resolve to the canonical one.
159 /// If `value` is not registered yet, register the value as canonical value.
160 pub fn ensure(&mut self, value: &str) -> T {
161 match self.resolve(value) {
162 Some(found) => found,
163 None => self.insert_canonical_impl(value),
164 }
165 }
166
167 /// Inserts given `value` as always canonical.
168 /// Fails if the given value is already registered.
169 ///
170 /// ```
171 #[doc = doctest_file::include_doctest!("src/doctests/direct_myinterned.rs", hidden)]
172 /// use bumpalo_intern::direct::{DirectInternStore, OccupiedError, StoredValue};
173 ///
174 /// let arena = bumpalo::Bump::new();
175 /// let mut interner = DirectInternStore::new(&arena);
176 /// let foo: MyInterned<'_> = interner.try_insert("foo").unwrap();
177 ///
178 /// let err = interner.try_insert("foo").unwrap_err();
179 /// assert_eq!(OccupiedError { existing: StoredValue::Canonical(foo) }, err);
180 /// ```
181 pub fn try_insert(&mut self, value: &str) -> Result<T, OccupiedError<'arena, T>> {
182 match self.get(value) {
183 None => Ok(self.insert_canonical_impl(value)),
184 Some(existing) => Err(OccupiedError { existing }),
185 }
186 }
187
188 /// Registers the given `value` as the alias of `canonical`.
189 /// Returns error if given `value` is already registered as different alias / canonical.
190 ///
191 /// ```
192 #[doc = doctest_file::include_doctest!("src/doctests/direct_myinterned.rs", hidden)]
193 /// use bumpalo_intern::direct::DirectInternStore;
194 ///
195 /// let arena = bumpalo::Bump::new();
196 /// let mut interner = DirectInternStore::new(&arena);
197 ///
198 /// let foo: MyInterned<'_> = interner.ensure(&"foo".to_string());
199 /// interner.register_alias("foo_alias", foo).unwrap();
200 /// assert_eq!(Some(foo), interner.resolve("foo_alias"));
201 ///
202 /// // idempotent alias is allowed.
203 /// interner.register_alias("foo_alias", foo).unwrap();
204 ///
205 /// // different alias is not allowed.
206 /// let bar = interner.ensure(&"bar".to_string());
207 /// interner.register_alias("foo_alias", bar).unwrap_err();
208 /// ```
209 pub fn register_alias(
210 &mut self,
211 value: &str,
212 canonical: T,
213 ) -> Result<(), OccupiedError<'arena, T>> {
214 match self.get(value) {
215 Some(StoredValue::Alias {
216 canonical: current, ..
217 }) if canonical.as_interned() == current.as_interned() => Ok(()),
218 Some(existing) => Err(OccupiedError { existing }),
219 None => {
220 self.insert_alias_impl(value, canonical.as_interned());
221 Ok(())
222 }
223 }
224 }
225
226 /// Returns the specified value if found, otherwise None.
227 ///
228 /// ```
229 #[doc = doctest_file::include_doctest!("src/doctests/direct_myinterned.rs", hidden)]
230 /// use bumpalo_intern::direct::DirectInternStore;
231 ///
232 /// let arena = bumpalo::Bump::new();
233 /// let mut interner = DirectInternStore::new(&arena);
234 /// let foo: MyInterned<'_> = interner.ensure("foo");
235 ///
236 /// assert_eq!(Some(foo), interner.resolve("foo"));
237 /// assert_eq!(None, interner.resolve("bar"));
238 /// ```
239 pub fn resolve(&self, value: &str) -> Option<T> {
240 let x = self.get(value)?;
241 Some(x.as_canonical())
242 }
243
244 /// Returns the Iterator for all elements.
245 ///
246 /// ```
247 #[doc = doctest_file::include_doctest!("src/doctests/direct_myinterned.rs", hidden)]
248 /// use bumpalo_intern::direct::{DirectInternStore, StoredValue};
249 ///
250 /// let arena = bumpalo::Bump::new();
251 /// let mut interner = DirectInternStore::new(&arena);
252 /// let foo: MyInterned<'_> = interner.ensure("foo");
253 ///
254 /// let got: Vec<StoredValue<MyInterned<'_>>> = interner.iter().collect();
255 /// assert_eq!(vec![StoredValue::Canonical(foo)], got);
256 /// ```
257 pub fn iter<'container>(&'container self) -> Iter<'arena, 'container, T>
258 where
259 'arena: 'container,
260 {
261 Iter {
262 base: self.records.iter(),
263 phantom: PhantomData,
264 }
265 }
266
267 #[inline]
268 fn get(&self, value: &str) -> Option<StoredValue<'arena, T>> {
269 let v = match self.records.get_key_value(value)? {
270 (canonical, None) => StoredValue::Canonical(Self::as_type(canonical)),
271 (alias, Some(canonical)) => StoredValue::Alias {
272 alias,
273 canonical: T::from_interned(*canonical),
274 },
275 };
276 Some(v)
277 }
278
279 #[inline]
280 fn insert_canonical_impl(&mut self, value: &str) -> T {
281 let copied: &'arena str = self.allocator.alloc_str(value);
282 let ret = self.records.insert(copied, None);
283 debug_assert!(
284 ret.is_none(),
285 "insert must be called on non-existing key, but already found: {:#?}",
286 ret
287 );
288 Self::as_type(copied)
289 }
290
291 #[inline]
292 fn insert_alias_impl(&mut self, value: &str, canonical: InternedStr<'arena>) {
293 let copied: &'arena str = self.allocator.alloc_str(value);
294 let ret = self.records.insert(copied, Some(canonical));
295 debug_assert!(
296 ret.is_none(),
297 "insert must be called on non-existing key, but already found: {:#?}",
298 ret
299 );
300 }
301
302 #[inline]
303 fn as_type(s: &'arena str) -> T {
304 <T as FromInterned>::from_interned(InternedStr(s))
305 }
306}
307
308/// an iterator over the items of a `Interner`.
309/// Compared to the underlying HashSet iterator,
310/// this struct ensures the `T` type.
311pub struct Iter<'arena, 'container, T> {
312 base: std::collections::hash_map::Iter<'container, &'arena str, Option<InternedStr<'arena>>>,
313 phantom: PhantomData<T>,
314}
315
316fn to_interned<'arena, T: FromInterned<'arena>>(x: &'arena str) -> T {
317 <T as FromInterned>::from_interned(InternedStr(x))
318}
319
320impl<'arena, T> Iterator for Iter<'arena, '_, T>
321where
322 T: FromInterned<'arena>,
323{
324 type Item = StoredValue<'arena, T>;
325
326 fn next(&mut self) -> Option<Self::Item> {
327 self.base.next().map(|(key, value)| match value {
328 None => StoredValue::Canonical(to_interned(key)),
329 Some(value) => StoredValue::Alias {
330 alias: key,
331 canonical: <T as FromInterned>::from_interned(*value),
332 },
333 })
334 }
335}
336
337impl<'arena, T> FusedIterator for Iter<'arena, '_, T> where T: FromInterned<'arena> {}