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
use nodrop::NoDrop;
use std::borrow::Borrow;
use std::collections::HashSet;
use std::hash::{self, Hash};
use std::sync::RwLock;

// ++++++++++++++++++++ Constant ++++++++++++++++++++

struct Constant<T>
    where T: ToOwned + ?Sized
{
    value: NoDrop<Box<T::Owned>>,
}

impl<T> Constant<T>
    where T: ToOwned + ?Sized
{
    fn new(value: T::Owned) -> Self { Self { value: NoDrop::new(Box::new(value)) } }

    fn as_static_ref(&self) -> &'static T::Owned {
        unsafe { &*(&**self.value as *const T::Owned) }
    }
}

impl<T> Borrow<T> for Constant<T>
    where T: ToOwned + ?Sized
{
    fn borrow(&self) -> &T { (&**self.value).borrow() }
}

impl<T> Hash for Constant<T>
    where T: ToOwned + ?Sized, T::Owned: Hash
{
    fn hash<H>(&self, state: &mut H)
        where H: hash::Hasher
    {
        self.value.hash(state)
    }
}

impl<T> PartialEq for Constant<T>
    where T: ToOwned + ?Sized, T::Owned: PartialEq
{
    fn eq(&self, other: &Self) -> bool { &**self.value == &**other.value }
}

impl<T> Eq for Constant<T> where T: ToOwned + ?Sized, T::Owned: Eq {}

// ++++++++++++++++++++ Pool ++++++++++++++++++++

pub struct Pool<T>
    where T: ToOwned + ?Sized
{
    consts: RwLock<HashSet<Constant<T>>>,
}

impl<T> Pool<T>
    where T: ToOwned + ?Sized, T::Owned: Hash + Eq, T: Hash + Eq
{
    pub fn new() -> Self { Pool { consts: Default::default() } }

    /// `U` may be `T` or `T::Owned`
    pub fn intern<U>(&self, value: U) -> &'static T::Owned
        where U: Borrow<T>, U: Into<T::Owned>
    {
        let mut consts = self.consts.write().unwrap();
        if let Some(c) = consts.get(value.borrow()) {
            return c.as_static_ref();
        }
        let c = Constant::new(value.into());
        let r = c.as_static_ref();
        consts.insert(c);
        r
    }
}