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
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash};
pub trait Poolable {
fn capacity(&self) -> usize;
fn alloc(size: usize) -> Self;
}
impl<T: Default + Clone> Poolable for Vec<T> {
fn capacity(&self) -> usize {
self.capacity()
}
fn alloc(size: usize) -> Self {
vec![T::default(); size]
}
}
impl<K, V, S> Poolable for HashMap<K, V, S>
where
K: Eq + Hash,
S: BuildHasher + Default,
{
fn capacity(&self) -> usize {
self.capacity()
}
fn alloc(size: usize) -> Self {
HashMap::with_capacity_and_hasher(size, Default::default())
}
}
pub trait Realloc {
fn realloc(&mut self, new_size: usize);
}
impl<T: Default + Clone> Realloc for Vec<T> {
fn realloc(&mut self, new_size: usize) {
use std::cmp::Ordering::*;
assert!(new_size > 0);
match new_size.cmp(&self.capacity()) {
Greater => self.resize(new_size, T::default()),
Less => {
self.truncate(new_size);
self.shrink_to_fit();
}
Equal => {}
}
}
}
impl<K, V, S> Realloc for HashMap<K, V, S>
where
K: Eq + Hash,
S: BuildHasher,
{
fn realloc(&mut self, new_size: usize) {
use std::cmp::Ordering::*;
assert!(new_size > 0);
match new_size.cmp(&self.capacity()) {
Greater => {
let current = self.capacity();
let diff = new_size - current;
self.reserve(diff);
}
Less => {
self.shrink_to_fit();
}
Equal => {}
}
}
}