internment 0.8.6

Easy interning of data
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
#![deny(missing_docs)]
use crate::boxedset::HashSet;
use std::borrow::Borrow;
use std::hash::{Hash, Hasher};
use std::sync::Mutex;

/// A arena for storing interned data
///
/// You can use an `Arena<T>` to intern data of type `T`.  This data is then
/// freed when the `Arena` is dropped.  An arena can hold some kinds of `!Sized`
/// data, such as `str`.
///
/// # Example
/// ```
/// let arena = internment::Arena::<str>::new();
/// // You can intern a `&str` object.
/// let x = arena.intern("world");
/// // You can also intern a `String`, in which case the data will not be copied
/// // if the value has not yet been interned.
/// let y = arena.intern_string(format!("hello {}", x));
/// // Interning a boxed `str` will also never require copying the data.
/// let v: Box<str> = "hello world".into();
/// let z = arena.intern_box(v);
/// // Any comparison of interned values will only need to check that the pointers
/// // are equal and will thus be fast.
/// assert_eq!(y, z);
/// assert!(x != z);
/// ```
///
/// # Another example
/// ```rust
/// use internment::Arena;
/// let arena: Arena<&'static str> = Arena::new();
/// let x = arena.intern("hello");
/// let y = arena.intern("world");
/// assert_ne!(x, y);
/// println!("The conventional greeting is '{} {}'", x, y);
/// ```

#[cfg_attr(docsrs, doc(cfg(feature = "arena")))]
pub struct Arena<T: ?Sized> {
    data: Mutex<HashSet<Box<T>>>,
}

#[cfg(feature = "deepsize")]
impl<T: ?Sized + deepsize::DeepSizeOf> deepsize::DeepSizeOf for Arena<T> {
    fn deep_size_of_children(&self, context: &mut deepsize::Context) -> usize {
        let hashset = self.data.lock().unwrap();
        (*hashset).deep_size_of_children(context)
    }
}

/// An interned object reference with the data stored in an `Arena<T>`.
#[cfg_attr(docsrs, doc(cfg(feature = "arena")))]
pub struct ArenaIntern<'a, T: ?Sized> {
    pointer: &'a T,
}

#[cfg(feature = "deepsize")]
impl<'a, T: ?Sized + deepsize::DeepSizeOf> deepsize::DeepSizeOf for ArenaIntern<'a, T> {
    fn deep_size_of_children(&self, _context: &mut deepsize::Context) -> usize {
        std::mem::size_of::<&T>()
    }
}

impl<'a, T: ?Sized> Clone for ArenaIntern<'a, T> {
    #[inline(always)]
    fn clone(&self) -> Self {
        *self
    }
}
impl<'a, T: ?Sized> Copy for ArenaIntern<'a, T> {}

impl<T: ?Sized> Arena<T> {
    /// Allocate a new `Arena`
    #[inline]
    pub fn new() -> Self {
        Arena {
            data: Mutex::new(HashSet::new()),
        }
    }
}
impl<T: Eq + Hash> Arena<T> {
    /// Intern a value.
    ///
    /// If this value has not previously been interned, then `intern` will
    /// allocate a spot for the value on the heap.  Otherwise, it will return a
    /// pointer to the object previously allocated.
    pub fn intern(&self, val: T) -> ArenaIntern<T> {
        let mut m = self.data.lock().unwrap();
        if let Some(b) = m.get(&val) {
            let p = b.as_ref() as *const T;
            return ArenaIntern {
                pointer: unsafe { &*p },
            };
        }
        let b = Box::new(val);
        let p = b.as_ref() as *const T;
        m.insert(b);
        ArenaIntern {
            pointer: unsafe { &*p },
        }
    }
}
impl<T: Eq + Hash + ?Sized> Arena<T> {
    /// Tedst
    pub fn intern_ref<'a, 'b, I>(&'a self, val: &'b I) -> ArenaIntern<'a, T>
    where
        T: 'a + Borrow<I>,
        Box<T>: From<&'b I>,
        I: Eq + std::hash::Hash + ?Sized,
    {
        let mut m = self.data.lock().unwrap();
        if let Some(b) = m.get(val) {
            let p = b.as_ref() as *const T;
            return ArenaIntern {
                pointer: unsafe { &*p },
            };
        }
        let b: Box<T> = val.into();
        let p = b.as_ref() as *const T;
        m.insert(b);
        ArenaIntern {
            pointer: unsafe { &*p },
        }
    }
    fn intern_from_owned<I>(&self, val: I) -> ArenaIntern<T>
    where
        Box<T>: From<I>,
        I: Eq + std::hash::Hash + AsRef<T>,
    {
        let mut m = self.data.lock().unwrap();
        if let Some(b) = m.get(val.as_ref()) {
            let p = b.as_ref() as *const T;
            return ArenaIntern {
                pointer: unsafe { &*p },
            };
        }
        let b: Box<T> = val.into();
        let p = b.as_ref() as *const T;
        m.insert(b);
        ArenaIntern {
            pointer: unsafe { &*p },
        }
    }
}
impl Arena<str> {
    /// Intern a `&str` as `ArenaIntern<str>`.
    ///
    /// If this value has not previously been interned, then `intern` will
    /// allocate a spot for the value on the heap.  Otherwise, it will return a
    /// pointer to the `str` previously allocated.
    #[inline]
    pub fn intern<'a>(&'a self, val: &str) -> ArenaIntern<'a, str> {
        self.intern_ref(val)
    }
    /// Intern a `String` as `ArenaIntern<str>`.
    ///
    /// If this value has not previously been interned, then `intern` will save
    /// the provided `String`.  Otherwise, it will free its input `String` and
    /// return a pointer to the `str` previously saved.
    #[inline]
    pub fn intern_string(&self, val: String) -> ArenaIntern<str> {
        self.intern_from_owned(val)
    }
    /// Intern a `Box<str>` as `ArenaIntern<str>`.
    ///
    /// If this value has not previously been interned, then `intern` will save
    /// the provided `Box<str>`.  Otherwise, it will free its input `Box<str>`
    /// and return a pointer to the `str` previously saved.
    #[inline]
    pub fn intern_box(&self, val: Box<str>) -> ArenaIntern<str> {
        self.intern_from_owned(val)
    }
}
impl Arena<std::ffi::CStr> {
    /// Intern a `&CStr` as `ArenaIntern<CStr>`.
    ///
    /// If this value has not previously been interned, then `intern` will
    /// allocate a spot for the value on the heap.  Otherwise, it will return a
    /// pointer to the `CStr` previously allocated.
    ///
    /// # Example
    /// ```
    /// # use internment::Arena;
    /// # let arena = Arena::<std::ffi::CStr>::new();
    /// let x = arena.intern(std::ffi::CString::new("hello").unwrap().as_c_str());
    /// let y = arena.intern(std::ffi::CString::new("hello").unwrap().as_c_str());
    /// assert_eq!(x, y);
    /// ```
    #[inline]
    pub fn intern<'a>(&'a self, val: &std::ffi::CStr) -> ArenaIntern<'a, std::ffi::CStr> {
        self.intern_ref(val)
    }
    /// Intern a `CString` as `ArenaIntern<CStr>`.
    ///
    /// If this value has not previously been interned, then `intern` will save
    /// the provided `CString`.  Otherwise, it will free its input `CString` and
    /// return a pointer to the `CStr` previously saved.
    ///
    /// # Example
    /// ```
    /// # use internment::Arena;
    /// # let arena = Arena::<std::ffi::CStr>::new();
    /// let x = arena.intern_cstring(std::ffi::CString::new("hello").unwrap());
    /// let y = arena.intern_cstring(std::ffi::CString::new("hello").unwrap());
    /// assert_eq!(x, y);
    /// ```
    #[inline]
    pub fn intern_cstring(&self, val: std::ffi::CString) -> ArenaIntern<std::ffi::CStr> {
        self.intern_from_owned(val)
    }
    /// Intern a `Box<CStr>` as `ArenaIntern<CStr>`.
    ///
    /// If this value has not previously been interned, then `intern` will save
    /// the provided `Box<CStr>`.  Otherwise, it will free its input `Box<CStr>`
    /// and return a pointer to the `CStr` previously saved.
    ///
    /// # Example
    /// ```
    /// # use internment::Arena;
    /// # let arena = Arena::<std::ffi::CStr>::new();
    /// let x = arena.intern_cstring(std::ffi::CString::new("hello").unwrap());
    /// let y = arena.intern_box(std::ffi::CString::new("hello").unwrap().into_boxed_c_str());
    /// assert_eq!(x, y);
    /// ```
    #[inline]
    pub fn intern_box(&self, val: Box<std::ffi::CStr>) -> ArenaIntern<std::ffi::CStr> {
        self.intern_from_owned(val)
    }
}
impl Arena<std::ffi::OsStr> {
    /// Intern a `&OsStr` as `ArenaIntern<OsStr>`.
    ///
    /// If this value has not previously been interned, then `intern` will
    /// allocate a spot for the value on the heap.  Otherwise, it will return a
    /// pointer to the `OsStr` previously allocated.
    ///
    /// # Example
    /// ```
    /// # use internment::Arena;
    /// # let arena = Arena::<std::ffi::OsStr>::new();
    /// let x = arena.intern(std::ffi::OsStr::new("hello"));
    /// let y = arena.intern(std::ffi::OsStr::new("hello"));
    /// assert_eq!(x, y);
    /// ```
    #[inline]
    pub fn intern<'a>(&'a self, val: &std::ffi::OsStr) -> ArenaIntern<'a, std::ffi::OsStr> {
        self.intern_ref(val)
    }
    /// Intern a `OsString` as `ArenaIntern<OsStr>`.
    ///
    /// If this value has not previously been interned, then `intern` will save
    /// the provided `OsString`.  Otherwise, it will free its input `OsString` and
    /// return a pointer to the `OsStr` previously saved.
    ///
    /// # Example
    /// ```
    /// # use internment::Arena;
    /// # let arena = Arena::<std::ffi::OsStr>::new();
    /// let x = arena.intern_osstring(std::ffi::OsString::from("hello"));
    /// let y = arena.intern_osstring(std::ffi::OsString::from("hello"));
    /// assert_eq!(x, y);
    /// ```
    #[inline]
    pub fn intern_osstring(&self, val: std::ffi::OsString) -> ArenaIntern<std::ffi::OsStr> {
        self.intern_from_owned(val)
    }
    /// Intern a `Box<OsStr>` as `ArenaIntern<OsStr>`.
    ///
    /// If this value has not previously been interned, then `intern` will save
    /// the provided `Box<OsStr>`.  Otherwise, it will free its input `Box<OsStr>`
    /// and return a pointer to the `OsStr` previously saved.
    ///
    /// # Example
    /// ```
    /// # use internment::Arena;
    /// # let arena = Arena::<std::ffi::OsStr>::new();
    /// let x = arena.intern_osstring(std::ffi::OsString::from("hello"));
    /// let y = arena.intern_box(std::ffi::OsString::from("hello").into_boxed_os_str());
    /// assert_eq!(x, y);
    /// ```
    #[inline]
    pub fn intern_box(&self, val: Box<std::ffi::OsStr>) -> ArenaIntern<std::ffi::OsStr> {
        self.intern_from_owned(val)
    }
}
impl Arena<std::path::Path> {
    /// Intern a `&Path` as `ArenaIntern<Path>`.
    ///
    /// If this value has not previously been interned, then `intern` will
    /// allocate a spot for the value on the heap.  Otherwise, it will return a
    /// pointer to the `Path` previously allocated.
    ///
    /// # Example
    /// ```
    /// # use internment::Arena;
    /// # let arena = Arena::<std::path::Path>::new();
    /// let x = arena.intern(std::path::Path::new("hello"));
    /// let y = arena.intern(std::path::Path::new("hello"));
    /// assert_eq!(x, y);
    /// ```
    #[inline]
    pub fn intern<'a>(&'a self, val: &std::path::Path) -> ArenaIntern<'a, std::path::Path> {
        self.intern_ref(val)
    }
    /// Intern a `PathBuf` as `ArenaIntern<Path>`.
    ///
    /// If this value has not previously been interned, then `intern` will save
    /// the provided `PathBuf`.  Otherwise, it will free its input `PathBuf` and
    /// return a pointer to the `Path` previously saved.
    ///
    /// # Example
    /// ```
    /// # use internment::Arena;
    /// # let arena = Arena::<std::path::Path>::new();
    /// let x = arena.intern_pathbuf(std::path::PathBuf::from("hello"));
    /// let y = arena.intern_pathbuf(std::path::PathBuf::from("hello"));
    /// assert_eq!(x, y);
    /// ```
    #[inline]
    pub fn intern_pathbuf(&self, val: std::path::PathBuf) -> ArenaIntern<std::path::Path> {
        self.intern_from_owned(val)
    }
    /// Intern a `Box<Path>` as `ArenaIntern<Path>`.
    ///
    /// If this value has not previously been interned, then `intern` will save
    /// the provided `Box<Path>`.  Otherwise, it will free its input `Box<Path>`
    /// and return a pointer to the `Path` previously saved.
    ///
    /// # Example
    /// ```
    /// # use internment::Arena;
    /// # let arena = Arena::<std::path::Path>::new();
    /// let x = arena.intern_pathbuf(std::path::PathBuf::from("hello"));
    /// let y = arena.intern_box(std::path::PathBuf::from("hello").into_boxed_path());
    /// assert_eq!(x, y);
    /// ```
    #[inline]
    pub fn intern_box(&self, val: Box<std::path::Path>) -> ArenaIntern<std::path::Path> {
        self.intern_from_owned(val)
    }
}
impl<T: Eq + Hash + Copy> Arena<[T]> {
    /// Intern a `&[T]` as `ArenaIntern<[T]>`.
    ///
    /// If this value has not previously been interned, then `intern` will
    /// allocate a spot for the value on the heap.  Otherwise, it will return a
    /// pointer to the `[T]` previously allocated.
    #[inline]
    pub fn intern<'a>(&'a self, val: &[T]) -> ArenaIntern<'a, [T]> {
        self.intern_ref(val)
    }
    /// Intern a `Vec<T>` as `ArenaIntern<[T]>`.
    ///
    /// If this value has not previously been interned, then `intern` will save
    /// the provided `Vec<T>`.  Otherwise, it will free its input `Vec<T>` and
    /// return a pointer to the `[T]` previously saved.
    #[inline]
    pub fn intern_vec(&self, val: Vec<T>) -> ArenaIntern<[T]> {
        self.intern_from_owned(val)
    }
    /// Intern a `Box<[T]>` as `ArenaIntern<[T]>`.
    ///
    /// If this value has not previously been interned, then `intern` will save
    /// the provided `Box<CSr>`.  Otherwise, it will free its input `Box<[T]>`
    /// and return a pointer to the `[T]` previously saved.
    #[inline]
    pub fn intern_box(&self, val: Box<[T]>) -> ArenaIntern<[T]> {
        self.intern_from_owned(val)
    }
}
impl<T: Eq + Hash + ?Sized> Arena<T> {
    /// Intern a reference to a type that can be converted into a `Box<T>` as `ArenaIntern<T>`.
    pub fn intern_from<'a, 'b, I>(&'a self, val: &'b I) -> ArenaIntern<'a, T>
    where
        T: 'a + Borrow<I> + From<&'b I>,
        I: Eq + std::hash::Hash + ?Sized,
    {
        let mut m = self.data.lock().unwrap();
        if let Some(b) = m.get(val) {
            let p = b.as_ref() as *const T;
            return ArenaIntern {
                pointer: unsafe { &*p },
            };
        }
        let b: Box<T> = Box::new(val.into());
        let p = b.as_ref() as *const T;
        m.insert(b);
        ArenaIntern {
            pointer: unsafe { &*p },
        }
    }
}

impl<T> Default for Arena<T> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<'a, T: ?Sized> AsRef<T> for ArenaIntern<'a, T> {
    #[inline(always)]
    fn as_ref(&self) -> &T {
        self.pointer
    }
}

impl<'a, T: ?Sized> std::ops::Deref for ArenaIntern<'a, T> {
    type Target = T;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl<'a, T: ?Sized> ArenaIntern<'a, T> {
    #[inline(always)]
    fn get_pointer(&self) -> *const T {
        self.pointer as *const T
    }

    /// Get a reference to a value interned into an arena.
    ///
    /// This function allows you to store values into a structure
    /// inline, without having to take a `&'a` reference to an
    /// `ArenaIntern<'a, T>`. This is required as using
    /// [`std::ops::Deref`] or [`std::convert::AsRef`]
    /// requires a `&self` receiver, but doing so, due to the bounds
    /// of these traits' functions, would implicitly require that
    /// this reference lives for `'a`.
    ///
    /// # Example
    ///
    /// Consider the following structures.
    /// ```rust
    /// # use internment::ArenaIntern;
    /// struct Bar {
    ///     baz: String,
    /// }
    ///
    /// struct Foo<'a>(ArenaIntern<'a, Bar>);
    /// ```
    ///
    /// The following code does not compile.
    /// ```compile_fail
    /// # use internment::ArenaIntern;
    /// # struct Bar {
    /// #     baz: String,
    /// # }
    /// #
    /// # struct Foo<'a>(ArenaIntern<'a, Bar>);
    /// #
    /// impl<'a> Foo<'a> {
    ///     pub fn get_baz(self) -> &'a str {
    ///         &self.0.as_ref().baz
    ///         // ^^^ ERROR: cannot return value referencing local data `self.0`
    ///     }
    /// }
    /// ```
    ///
    /// This similar code, which uses `into_ref`, does compile.
    /// ```rust
    /// # use internment::ArenaIntern;
    /// # struct Bar {
    /// #     baz: String,
    /// # }
    /// #
    /// # struct Foo<'a>(ArenaIntern<'a, Bar>);
    /// #
    /// impl<'a> Foo<'a> {
    ///     pub fn get_baz(self) -> &'a str {
    ///         &self.0.into_ref().baz
    ///     }
    /// }
    /// ```
    #[inline(always)]
    pub fn into_ref(self) -> &'a T {
        self.pointer
    }
}

/// The hash implementation returns the hash of the pointer
/// value, not the hash of the value pointed to.  This should
/// be irrelevant, since there is a unique pointer for every
/// value, but it *is* observable, since you could compare the
/// hash of the pointer with hash of the data itself.
impl<'a, T: ?Sized> Hash for ArenaIntern<'a, T> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.get_pointer().hash(state);
    }
}

impl<'a, T: ?Sized> PartialEq for ArenaIntern<'a, T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self.get_pointer(), other.get_pointer())
    }
}
impl<'a, T: ?Sized> Eq for ArenaIntern<'a, T> {}

// #[cfg(feature = "arena")]
// create_impls_no_new!(ArenaIntern, arenaintern_impl_tests, ['a], [Eq, Hash], [Eq, Hash]);

impl<'a, T: std::fmt::Debug + ?Sized> std::fmt::Debug for ArenaIntern<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        self.as_ref().fmt(f)
    }
}

impl<'a, T: std::fmt::Display + ?Sized> std::fmt::Display for ArenaIntern<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        self.as_ref().fmt(f)
    }
}

#[test]
fn eq_string() {
    let arena = Arena::<&'static str>::new();
    assert_eq!(arena.intern("hello"), arena.intern("hello"));
    assert_ne!(arena.intern("goodbye"), arena.intern("farewell"));
}
#[test]
fn display() {
    let arena = Arena::<&'static str>::new();
    let world = arena.intern("world");
    println!("Hello {}", world);
}
#[test]
fn debug() {
    let arena = Arena::<&'static str>::new();
    let world = arena.intern("world");
    println!("Hello {:?}", world);
}
#[test]
fn can_clone() {
    let arena = Arena::<&'static str>::new();
    assert_eq!(arena.intern("hello").clone(), arena.intern("hello"));
}
#[test]
fn has_deref() {
    let arena = Arena::<Option<String>>::new();
    let x = arena.intern(None);
    let b: &Option<String> = x.as_ref();
    use std::ops::Deref;
    assert_eq!(b, arena.intern(None).deref());
}

#[test]
fn unsized_str() {
    let arena = Arena::<str>::new();
    let x = arena.intern("hello");
    let b: &str = x.as_ref();
    assert_eq!("hello", b);
}

#[test]
fn ref_to_string() {
    let arena = Arena::<String>::new();
    let x = arena.intern_from("hello");
    assert_eq!("hello", &*x);
}