-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpoolable.rs
122 lines (102 loc) · 2.6 KB
/
poolable.rs
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
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash};
/// The trait required to be able to use a type in `BytePool`.
pub trait Poolable {
fn empty(&self) -> bool;
fn len(&self) -> usize;
fn capacity(&self) -> usize;
fn resize(&mut self, count: usize);
fn reset(&mut self);
fn alloc(size: usize) -> Self;
fn alloc_and_fill(size: usize) -> Self;
}
impl<T: Default + Clone> Poolable for Vec<T> {
fn empty(&self) -> bool {
self.len() == 0
}
fn len(&self) -> usize {
self.len()
}
fn capacity(&self) -> usize {
self.capacity()
}
fn resize(&mut self, count: usize) {
self.resize(count, T::default());
}
fn reset(&mut self) {
self.clear();
}
fn alloc(size: usize) -> Self {
Vec::<T>::with_capacity(size)
}
fn alloc_and_fill(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 empty(&self) -> bool {
self.len() == 0
}
fn len(&self) -> usize {
self.len()
}
fn capacity(&self) -> usize {
self.capacity()
}
fn resize(&mut self, _count: usize) {
// do thing
}
fn reset(&mut self) {
self.clear();
}
fn alloc(size: usize) -> Self {
Self::alloc_and_fill(size)
}
fn alloc_and_fill(size: usize) -> Self {
// not actually filling the HaspMap though
HashMap::with_capacity_and_hasher(size, Default::default())
}
}
/// A trait allowing for efficient reallocation.
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.reserve(new_size - self.capacity()),
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 => {}
}
}
}