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
#![deny(missing_docs)]
use crate::boxedset::HashSet;
use parking_lot::Mutex;
use std::borrow::Borrow;
use std::hash::{Hash, Hasher};

/// 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>>>,
}
/// 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,
}

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

impl<T: ?Sized> Arena<T> {
    /// Allocate a new `Arena`
    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();
        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();
        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();
        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.
    pub fn intern<'a, 'b>(&'a self, val: &'b 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.
    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.
    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.
    pub fn intern<'a, 'b>(&'a self, val: &'b 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.
    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<CSr>`.  Otherwise, it will free its input `Box<CStr>`
    /// and return a pointer to the `CStr` previously saved.
    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.
    pub fn intern<'a, 'b>(&'a self, val: &'b 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.
    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<CSr>`.  Otherwise, it will free its input `Box<OsStr>`
    /// and return a pointer to the `OsStr` previously saved.
    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.
    pub fn intern<'a, 'b>(&'a self, val: &'b 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.
    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<CSr>`.  Otherwise, it will free its input `Box<Path>`
    /// and return a pointer to the `Path` previously saved.
    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.
    pub fn intern<'a, 'b>(&'a self, val: &'b [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.
    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.
    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();
        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> {
    fn default() -> Self {
        Self::new()
    }
}

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

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

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

/// 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> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.get_pointer().hash(state);
    }
}

impl<'a, T: ?Sized> PartialEq for ArenaIntern<'a, T> {
    fn eq(&self, other: &Self) -> bool {
        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> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        std::fmt::Debug::fmt(&self.get_pointer(), f)?;
        f.write_str(" : ")?;
        self.as_ref().fmt(f)
    }
}

impl<'a, T: std::fmt::Display + ?Sized> std::fmt::Display for ArenaIntern<'a, T> {
    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);
}