Skip to content

Commit 5724886

Browse files
two lists, split between sizes
1 parent d2dc7a6 commit 5724886

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/lib.rs

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,13 @@ use std::sync::Mutex;
3434
/// A pool of byte slices, that reuses memory.
3535
#[derive(Debug)]
3636
pub struct BytePool {
37-
list: Mutex<Vec<Vec<u8>>>,
37+
list_large: Mutex<Vec<Vec<u8>>>,
38+
list_small: Mutex<Vec<Vec<u8>>>,
3839
}
3940

41+
/// The size at which point values are allocated in the small list, rather than the big.
42+
const SPLIT_SIZE: usize = 4 * 1024;
43+
4044
/// The value returned by an allocation of the pool.
4145
/// When it is dropped the memory gets returned into the pool, and is not zeroed.
4246
/// If that is a concern, you must clear the data yourself.
@@ -54,7 +58,8 @@ impl fmt::Debug for Block<'_> {
5458
impl Default for BytePool {
5559
fn default() -> Self {
5660
BytePool {
57-
list: Mutex::new(Vec::new()),
61+
list_large: Mutex::new(Vec::new()),
62+
list_small: Mutex::new(Vec::new()),
5863
}
5964
}
6065
}
@@ -73,7 +78,11 @@ impl BytePool {
7378
assert!(size > 0, "Can not allocate empty blocks");
7479

7580
// check the last 4 blocks
76-
let mut lock = self.list.lock().unwrap();
81+
let mut lock = if size < SPLIT_SIZE {
82+
self.list_small.lock().unwrap()
83+
} else {
84+
self.list_large.lock().unwrap()
85+
};
7786
let end = lock.len();
7887
let start = if end > 4 { end - 4 } else { 0 };
7988

@@ -92,7 +101,11 @@ impl BytePool {
92101
}
93102

94103
fn push_raw_block(&self, block: Vec<u8>) {
95-
self.list.lock().unwrap().push(block);
104+
if block.capacity() < SPLIT_SIZE {
105+
self.list_small.lock().unwrap().push(block);
106+
} else {
107+
self.list_large.lock().unwrap().push(block);
108+
}
96109
}
97110
}
98111

@@ -228,6 +241,6 @@ mod tests {
228241
h2.join().unwrap();
229242

230243
// two threads allocating in parallel will need 2 buffers
231-
assert_eq!(pool.list.lock().unwrap().len(), 2);
244+
assert_eq!(pool.list_small.lock().unwrap().len(), 2);
232245
}
233246
}

0 commit comments

Comments
 (0)