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
245
use std::fmt;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;
use crossbeam_queue::SegQueue;
#[derive(Debug)]
pub struct BytePool {
list_large: SegQueue<Vec<u8>>,
list_small: SegQueue<Vec<u8>>,
}
const SPLIT_SIZE: usize = 4 * 1024;
pub struct Block<'a> {
data: mem::ManuallyDrop<Vec<u8>>,
pool: &'a BytePool,
}
impl fmt::Debug for Block<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Block").field("data", &self.data).finish()
}
}
impl Default for BytePool {
fn default() -> Self {
BytePool {
list_large: SegQueue::new(),
list_small: SegQueue::new(),
}
}
}
impl BytePool {
pub fn new() -> Self {
BytePool::default()
}
pub fn alloc(&self, size: usize) -> Block<'_> {
assert!(size > 0, "Can not allocate empty blocks");
let list = if size < SPLIT_SIZE {
&self.list_small
} else {
&self.list_large
};
if let Ok(el) = list.pop() {
if el.capacity() == size {
return Block::new(el, self);
} else {
list.push(el);
}
}
let data = vec![0u8; size];
Block::new(data, self)
}
fn push_raw_block(&self, block: Vec<u8>) {
if block.capacity() < SPLIT_SIZE {
self.list_small.push(block);
} else {
self.list_large.push(block);
}
}
}
impl<'a> Drop for Block<'a> {
fn drop(&mut self) {
let data = mem::ManuallyDrop::into_inner(unsafe { ptr::read(&self.data) });
self.pool.push_raw_block(data);
}
}
impl<'a> Block<'a> {
fn new(data: Vec<u8>, pool: &'a BytePool) -> Self {
Block {
data: mem::ManuallyDrop::new(data),
pool,
}
}
pub fn realloc(&mut self, new_size: usize) {
use std::cmp::Ordering::*;
assert!(new_size > 0);
match new_size.cmp(&self.size()) {
Greater => self.data.resize(new_size, 0u8),
Less => {
self.data.truncate(new_size);
self.shrink_to_fit();
}
Equal => {}
}
}
pub fn size(&self) -> usize {
self.data.capacity()
}
}
impl<'a> Deref for Block<'a> {
type Target = Vec<u8>;
#[inline]
fn deref(&self) -> &Self::Target {
self.data.deref()
}
}
impl<'a> DerefMut for Block<'a> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
self.data.deref_mut()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basics() {
let pool = BytePool::new();
for i in 0..100 {
let mut block_1k = pool.alloc(1 * 1024);
let mut block_4k = pool.alloc(4 * 1024);
for el in block_1k.deref_mut() {
*el = i as u8;
}
for el in block_4k.deref_mut() {
*el = i as u8;
}
for el in block_1k.deref() {
assert_eq!(*el, i as u8);
}
for el in block_4k.deref() {
assert_eq!(*el, i as u8);
}
}
}
#[test]
fn realloc() {
let pool = BytePool::new();
let mut buf = pool.alloc(10);
let _slice: &[u8] = &buf;
assert_eq!(buf.capacity(), 10);
for i in 0..10 {
buf[i] = 1;
}
buf.realloc(512);
assert_eq!(buf.capacity(), 512);
for el in buf.iter().take(10) {
assert_eq!(*el, 1);
}
buf.realloc(5);
assert_eq!(buf.capacity(), 5);
for el in buf.iter() {
assert_eq!(*el, 1);
}
}
#[test]
fn multi_thread() {
let pool = std::sync::Arc::new(BytePool::new());
let pool1 = pool.clone();
let h1 = std::thread::spawn(move || {
for _ in 0..100 {
let mut buf = pool1.alloc(64);
buf[10] = 10;
}
});
let pool2 = pool.clone();
let h2 = std::thread::spawn(move || {
for _ in 0..100 {
let mut buf = pool2.alloc(64);
buf[10] = 10;
}
});
h1.join().unwrap();
h2.join().unwrap();
assert!(pool.list_small.len() <= 2);
}
}