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
//! The Intern Pool  


use std::{
    borrow::Borrow,
    ffi::OsStr,
    hash::Hash,
    ops::Deref,
    sync::{Arc, RwLock},
};

use dashmap::DashSet;
use once_cell::sync::Lazy;

/// The String Intern Pool  

pub static STR_POOL: Lazy<Pool<str>> = Lazy::new(|| Pool::new());

/// The OsString Intern Pool  

pub static OS_STR_POOL: Lazy<Pool<OsStr>> = Lazy::new(|| Pool::new());

/// The Intern Pool  

#[derive(Debug)]
pub struct Pool<T: Eq + Hash + ?Sized> {
    pool: DashSet<Arc<T>>,
    gc_lock: RwLock<()>,
}

impl<T: Eq + Hash + ?Sized> Pool<T> {
    /// New a empty intern pool

    #[inline]
    pub fn new() -> Self {
        Self {
            pool: DashSet::new(),
            gc_lock: RwLock::new(()),
        }
    }
}

impl<T: Eq + Hash + ?Sized> Pool<T> {
    /// Make a intern

    #[inline]
    pub fn intern<A: AsRef<T>>(&self, a: A, to_arc: impl FnOnce(A) -> Arc<T>) -> Intern<T> {
        match self.pool.get(a.as_ref()).map(|v| v.key().clone()) {
            Some(v) => Intern(v),
            None => {
                let arc = to_arc(a);
                Intern(self.insert_arc(arc))
            }
        }
    }

    #[inline]
    fn insert_arc(&self, arc: Arc<T>) -> Arc<T> {
        if self.pool.insert(Clone::clone(&arc)) {
            arc
        } else {
            self.when_failed(arc)
        }
    }

    #[cold]
    fn when_failed(&self, arc: Arc<T>) -> Arc<T> {
        let lock = self.gc_lock.read();
        let r = match self.pool.get(arc.as_ref()).map(|v| v.key().clone()) {
            Some(v) => v,
            None => {
                let s = self.pool.insert(Clone::clone(&arc));
                assert!(s);
                arc
            }
        };
        drop(lock);
        r
    }
}

impl<T: Eq + Hash + ?Sized> Pool<T> {
    /// Delete all interning string with reference count == 1 in the pool

    pub fn collect_garbage(&self) {
        let lock = self.gc_lock.write();
        self.pool.retain(|arc| Arc::<T>::strong_count(arc) > 1);
        drop(lock);
    }
}

/// Intern Ptr  

#[derive(Debug, Eq, Ord, PartialOrd)]
pub struct Intern<T: ?Sized>(Arc<T>);

impl<T: ?Sized> Intern<T> {
    /// Get target ref

    #[inline]
    pub fn get(&self) -> &T {
        self.0.as_ref()
    }
}

impl<T: ?Sized> PartialEq for Intern<T> {
    fn eq(&self, other: &Self) -> bool {
        std::sync::Arc::<T>::as_ptr(&self.0) == std::sync::Arc::<T>::as_ptr(&other.0)
    }
}

impl<T: ?Sized> Clone for Intern<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T: ?Sized> Deref for Intern<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.0.deref()
    }
}

impl<T: ?Sized> AsRef<T> for Intern<T> {
    fn as_ref(&self) -> &T {
        self.0.as_ref()
    }
}

impl<T: ?Sized> Borrow<T> for Intern<T> {
    fn borrow(&self) -> &T {
        self.0.borrow()
    }
}

impl<T: ?Sized> From<Intern<T>> for Arc<T> {
    fn from(v: Intern<T>) -> Self {
        v.0
    }
}

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

    #[test]
    fn test_basic() {
        let h = STR_POOL.intern("asd", Arc::from);
        assert_eq!(h.get(), "asd");
    }

    #[test]
    fn test_same() {
        let h1 = STR_POOL.intern("asd", Arc::from);
        let h2 = STR_POOL.intern("asd", Arc::from);
        assert_eq!(h1, h2);
        assert_eq!(h1.get(), "asd");
        assert_eq!(h2.get(), "asd");
    }

    #[test]
    fn test_not_same() {
        let h1 = STR_POOL.intern("asd", Arc::from);
        let h2 = STR_POOL.intern("123", Arc::from);
        assert_ne!(h1, h2);
        assert_eq!(h1.get(), "asd");
        assert_eq!(h2.get(), "123");
    }

    #[test]
    #[ignore]
    fn test_pool_gc() {
        assert_eq!(STR_POOL.pool.len(), 0);
        STR_POOL.intern("asd", Arc::from);
        assert_eq!(STR_POOL.pool.len(), 1);
        let h = STR_POOL.intern("123", Arc::from);
        assert_eq!(STR_POOL.pool.len(), 2);
        STR_POOL.collect_garbage();
        assert_eq!(STR_POOL.pool.len(), 1);
        drop(h);
        assert_eq!(STR_POOL.pool.len(), 1);
        STR_POOL.collect_garbage();
        assert_eq!(STR_POOL.pool.len(), 0);
    }

    #[test]
    fn test_concurrent_1() {
        use std::thread::spawn;

        let t: Vec<_> = (0..100)
            .into_iter()
            .map(|i| {
                spawn(move || {
                    let a = STR_POOL.intern(i.to_string(), Arc::from);
                    let v: Vec<_> = (0..100)
                        .into_iter()
                        .map(|_| spawn(move || STR_POOL.intern(i.to_string(), Arc::from)))
                        .collect();
                    for b in v.into_iter() {
                        assert_eq!(a, b.join().unwrap());
                    }
                })
            })
            .collect();

        for r in t.into_iter() {
            assert!(r.join().is_ok());
        }
    }

    #[test]
    fn test_concurrent_2_gc() {
        use std::thread::spawn;

        let t: Vec<_> = (0..100)
            .into_iter()
            .map(|i| {
                spawn(move || {
                    let v: Vec<_> = (0..100)
                        .into_iter()
                        .map(|_| spawn(move || STR_POOL.intern(i.to_string(), Arc::from)))
                        .collect();
                    for b in v.into_iter() {
                        assert_eq!(b.join().unwrap().get(), i.to_string());
                    }
                })
            })
            .zip((0..100).into_iter().map(|_| {
                spawn(move || {
                    let v: Vec<_> = (0..100)
                        .into_iter()
                        .map(|_| {
                            spawn(move || {
                                STR_POOL.collect_garbage();
                            })
                        })
                        .collect();
                    for r in v.into_iter() {
                        assert!(r.join().is_ok());
                    }
                })
            }))
            .collect();

        for (a, b) in t.into_iter() {
            assert!(a.join().is_ok());
            assert!(b.join().is_ok());
        }
    }
}