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
use chashmap::CHashMap;
use std::hash::Hash;
use std::sync::{Arc, Weak};
use crate::{Allocator, Id};
pub struct HashAllocator<T> {
backing: CHashMap<Arc<T>, Weak<T>>,
}
impl<T> Default for HashAllocator<T> {
fn default() -> Self {
let backing = CHashMap::new();
Self { backing }
}
}
impl<T: Eq + Hash> Allocator<T> for HashAllocator<T> {
fn allocate(&self, t: T) -> Id<T> {
let key = Arc::new(t);
let value = Arc::downgrade(&key);
let mut result = Arc::clone(&key);
self.backing.upsert(
key,
|| value,
|other| {
result = Weak::upgrade(other).unwrap();
},
);
Id(result)
}
fn allocations(&self) -> usize {
self.backing.len()
}
fn delete_unused(&self) {
self.backing
.retain(|key, _value| Arc::strong_count(key) > 1);
self.backing.shrink_to_fit();
}
}