hashcons-arena 0.1.0

A simple hash-consing arena
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! A hash consing arena for efficient interning of values.
//!
//! This arena allows you to intern values such that structurally equal values will yield the
//! same reference, thus saving memory and improving performance in scenarios where many
//! identical values are used.
//!
//! # Features
//!
//! - `sync`: Use a `RwLock`, rather than a `RefCell` to implement interior mutability. This
//! allows the arena to be [`Sync`]. Depends on the `parking_lot` crate.
//!
//! # Example
//!
//! ```rust,ignore
//! use hashcons_arena::HashConsArena;
//!
//! let arena = HashConsArena::new();
//! let a = arena.intern("hello");
//! let b = arena.intern("hello");
//!
//! assert!(a == b); // a and b are the same reference
//! ```
//!
//! # Safety
//!
//! The crate uses `unsafe` in a number of places, and has been tested using miri.
//!

#[cfg(not(feature = "sync"))]
use std::cell::RefCell as RC;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fmt::{self, Debug, Display};
use std::hash::{Hash, Hasher};
use std::mem;
use std::ops::Deref;
use std::pin::Pin;
use std::ptr::NonNull;

use bumpalo::Bump;
use bumpalo::boxed::Box;
use fxhash::hash64;
#[cfg(feature = "sync")]
use parking_lot::RwLock as RC;

#[cfg(feature = "sync")]
mod rc {
    use super::RC;

    #[inline(always)]
    pub(crate) fn read_table<T>(table: &RC<T>) -> parking_lot::RwLockReadGuard<'_, T> {
        table.read()
    }

    #[inline(always)]
    pub(crate) fn write_table<T>(table: &RC<T>) -> parking_lot::RwLockWriteGuard<'_, T> {
        table.write()
    }
}

#[cfg(not(feature = "sync"))]
mod rc {
    use super::RC;

    #[inline(always)]
    pub(crate) fn read_table<T>(table: &RC<T>) -> std::cell::Ref<'_, T> {
        table.borrow()
    }

    #[inline(always)]
    pub(crate) fn write_table<T>(table: &RC<T>) -> std::cell::RefMut<'_, T> {
        table.borrow_mut()
    }
}

/// A hash consing arena that allows for efficient interning of values.
///
/// ## Caveat(s)
///
/// The arena is backed by a [bumpalo](https://crates.io/crates/bumpalo), therefore, objects
/// allocated via the arena, will not have their [`Drop`] implementation called, without manual
/// intervention. Thus, it is relatively easy to leak resources. If you need [`Drop`] to be called,
/// use [`BoxedHashConsArena`] instead.
///
pub struct HashConsArena<T> {
    bump: Bump,
    table: RC<BTreeMap<u64, Vec<NonNull<T>>>>,
}

pub struct HRef<'a, T> {
    ptr: &'a T,
}

impl<'a, T> Clone for HRef<'a, T> {
    fn clone(&self) -> Self {
        Self { ptr: self.ptr }
    }
}

impl<'a, T> Copy for HRef<'a, T> {}

impl<'a, T> HRef<'a, T> {
    pub(crate) fn new(ptr: &'a T) -> Self {
        Self { ptr }
    }

    pub(crate) fn as_ptr(&self) -> *const T {
        self.ptr as *const T
    }

    pub fn as_ref(&self) -> &'a T {
        self.ptr
    }
}

impl<'a, T> Deref for HRef<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.ptr
    }
}

impl<'a, T> PartialEq for HRef<'a, T> {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self.ptr, other.ptr)
    }
}

impl<'a, T> PartialEq<T> for HRef<'a, T>
where
    T: PartialEq,
{
    fn eq(&self, other: &T) -> bool {
        self.as_ref() == other
    }
}

impl<'a, T> Eq for HRef<'a, T> {}

impl<'a, T> Hash for HRef<'a, T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // hash the pointer address, not the value
        self.as_ptr().hash(state);
    }
}

impl<'a, T> PartialOrd for HRef<'a, T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<'a, T> Ord for HRef<'a, T> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_ptr().cmp(&other.as_ptr())
    }
}

impl<'a, T> Debug for HRef<'a, T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HRef")
            .field("ptr", &(self.as_ptr() as usize))
            .field("val", &self.ptr)
            .finish()
    }
}

impl<'a, T> Display for HRef<'a, T>
where
    T: Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.ptr.fmt(f)
    }
}

impl<T> HashConsArena<T>
where
    T: Eq + Hash,
{
    /// Create a new `HashConsArena`.
    pub fn new() -> Self {
        Self {
            bump: Bump::new(),
            table: RC::new(BTreeMap::new()),
        }
    }

    /// Intern a value, returning a reference that's guaranteed to be the same for structurally
    /// equal values.
    ///
    /// # Arguments
    /// * `value` - The value to intern. It must implement `Eq` and `Hash`.
    ///
    /// # Returns
    /// A `HRef<T>` that points to the interned value. If the value is already interned, it returns
    /// the existing reference.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use hashcons_arena::HashConsArena;
    ///
    /// let arena = HashConsArena::new();
    ///
    /// let a = arena.intern("hello");
    /// let b = arena.intern("hello");
    ///
    /// assert!(a == b); // a and b are the same reference
    /// ```
    ///
    pub fn intern<'a>(&'a self, value: T) -> HRef<'a, T> {
        // compute hash of the value
        let hash = hash64(&value);

        // check if we already have this value
        {
            let table = rc::read_table(&self.table);
            if let Some(candidates) = table.get(&hash) {
                for &ptr in candidates {
                    let existing = unsafe { ptr.as_ref() };
                    if *existing == value {
                        // found
                        return HRef::new(existing);
                    }
                }
            }
        } // table borrow ends here

        // not found, allocate new one
        let allocated = &*self.bump.alloc(value);
        let ptr = NonNull::from(allocated);

        // add to hash table
        rc::write_table(&self.table)
            .entry(hash)
            .or_insert_with(Vec::new)
            .push(ptr);

        HRef::new(allocated)
    }

    /// Reset the arena, clearing all interned values.
    pub fn reset(&mut self) {
        rc::write_table(&self.table).clear();
        self.bump.reset();
    }
}

/// A version of `HashConsArena` that ensures interned values are dropped.
pub struct BoxedHashConsArena<T>
where
    T: 'static,
{
    bump: Bump,
    table: RC<BTreeMap<u64, Vec<Pin<Box<'static, T>>>>>,
}

impl<T> BoxedHashConsArena<T>
where
    T: Eq + Hash + 'static,
{
    /// Create a new `BoxedHashConsArena`.
    pub fn new() -> Self {
        Self {
            bump: Bump::new(),
            table: RC::new(BTreeMap::new()),
        }
    }

    /// Intern a value, returning a reference that's guaranteed to be the same for structurally
    /// equal values.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to intern. It must implement `Eq` and `Hash`.
    ///
    /// # Returns
    ///
    /// A `HRef<T>` that points to the interned value. If the value is already interned, it returns
    /// the existing reference.
    ///
    pub fn intern<'a>(&'a self, value: T) -> HRef<'a, T> {
        // compute hash of the value
        let hash = hash64(&value);

        // check if we already have this value
        {
            let table = rc::read_table(&self.table);
            if let Some(candidates) = table.get(&hash) {
                for existing in candidates {
                    if **existing == value {
                        // found - return reference with proper lifetime
                        // safety: the box lives as long as the arena, and we're borrowing
                        // from the arena with lifetime 'a, so this is safe
                        let existing_ref = unsafe { mem::transmute::<&T, &'a T>(existing.deref()) };
                        return HRef::new(existing_ref);
                    }
                }
            }
        } // table borrow ends here

        // not found, allocate new one
        let allocated = Box::pin_in(value, &self.bump);

        // safety: the box will live as long as the bump allocator, and we ensure
        // that the bump allocator is never reset while references exist
        let static_box =
            unsafe { mem::transmute::<Pin<Box<'_, T>>, Pin<Box<'static, T>>>(allocated) };

        // add to hash table first, then get reference from the stored location
        let mut table = rc::write_table(&self.table);

        let entry = table.entry(hash).or_insert_with(Vec::new);

        entry.push(static_box);

        // now get the reference from the box in its final storage location (pleasing miri)
        let stored_box = entry.last().unwrap();
        let allocated_ref = unsafe { mem::transmute::<&T, &'a T>(stored_box.deref()) };

        HRef::new(allocated_ref)
    }

    /// Reset the arena, clearing all interned values.
    pub fn reset(&mut self) {
        rc::write_table(&self.table).clear();
        self.bump.reset();
    }
}

impl<T> Drop for BoxedHashConsArena<T> {
    fn drop(&mut self) {
        // this is necessary to ensure that all boxes are dropped before the bump allocator
        // otherwise we might have dangling references
        rc::write_table(&self.table).clear();
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_interning() {
        let arena = HashConsArena::new();
        let a = arena.intern("hello");
        let b = arena.intern("hello");

        assert!(a == b); // a and b are the same reference
        assert_eq!(a, "hello");
    }

    #[test]
    fn test_multiple_arenas() {
        let arena1 = HashConsArena::new();
        let arena2 = HashConsArena::new();

        let a1 = arena1.intern("hello");
        let a2 = arena2.intern("hello");

        assert!(a1 != a2); // a1 and a2 are different references
        assert_eq!(a1, "hello");
        assert_eq!(a2, "hello");
    }

    #[test]
    fn test_drop() {
        use std::sync::Arc;
        use std::sync::atomic::AtomicUsize;

        let arena = BoxedHashConsArena::new();
        let drop_ctr = Arc::new(AtomicUsize::new(0));

        struct MyStr {
            value: String,
            drop_ctr: Arc<AtomicUsize>,
        }

        impl MyStr {
            fn new(value: impl Into<String>, drop_ctr: Arc<AtomicUsize>) -> Self {
                Self {
                    value: value.into(),
                    drop_ctr,
                }
            }
        }

        impl PartialEq for MyStr {
            fn eq(&self, other: &Self) -> bool {
                self.value == other.value
            }
        }

        impl Eq for MyStr {}

        impl Hash for MyStr {
            fn hash<H: Hasher>(&self, state: &mut H) {
                self.value.hash(state);
            }
        }

        impl Drop for MyStr {
            fn drop(&mut self) {
                self.drop_ctr
                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            }
        }

        let a = arena.intern(MyStr::new("hello", drop_ctr.clone()));
        let b = arena.intern(MyStr::new("world", drop_ctr.clone()));

        assert!(a != b); // a and b are different references

        // drop the arena, which should clear the table
        drop(arena);

        // check that the drop counter was incremented for both values
        assert_eq!(drop_ctr.load(std::sync::atomic::Ordering::SeqCst), 2);
    }

    #[test]
    fn test_reset() {
        let mut arena = HashConsArena::new();
        let _a = arena.intern("hello");
        assert_eq!(rc::read_table(&arena.table).len(), 1);
        arena.reset();
        assert_eq!(rc::read_table(&arena.table).len(), 0);
    }
}