Skip to content

Commit ca61d55

Browse files
authored
Merge pull request #229 from cloneable/bufferpool-optimization
Allow specifying an initial pooled buffer size
2 parents 0e8d22e + 53d6adb commit ca61d55

File tree

1 file changed

+21
-19
lines changed

1 file changed

+21
-19
lines changed

src/buffer_pool.rs

+21-19
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ use std::{mem::replace, ops::Deref, sync::Arc};
1111

1212
#[derive(Debug)]
1313
pub struct BufferPool {
14-
buffer_cap: usize,
14+
buffer_size_cap: usize,
15+
buffer_init_cap: usize,
1516
pool: ArrayQueue<Vec<u8>>,
1617
}
1718

@@ -22,25 +23,29 @@ impl BufferPool {
2223
.and_then(|x| x.parse().ok())
2324
.unwrap_or(128_usize);
2425

25-
let buffer_cap = std::env::var("MYSQL_ASYNC_BUFFER_SIZE_CAP")
26+
let buffer_size_cap = std::env::var("MYSQL_ASYNC_BUFFER_SIZE_CAP")
2627
.ok()
2728
.and_then(|x| x.parse().ok())
2829
.unwrap_or(4 * 1024 * 1024);
2930

31+
let buffer_init_cap = std::env::var("MYSQL_ASYNC_BUFFER_INIT_CAP")
32+
.ok()
33+
.and_then(|x| x.parse().ok())
34+
.unwrap_or(0);
35+
3036
Self {
3137
pool: ArrayQueue::new(pool_cap),
32-
buffer_cap,
38+
buffer_size_cap,
39+
buffer_init_cap,
3340
}
3441
}
3542

3643
pub fn get(self: &Arc<Self>) -> PooledBuf {
37-
let mut buf = self.pool.pop().unwrap_or_default();
38-
39-
// SAFETY:
40-
// 1. OK – 0 is always within capacity
41-
// 2. OK - nothing to initialize
42-
unsafe { buf.set_len(0) }
43-
44+
let buf = self
45+
.pool
46+
.pop()
47+
.unwrap_or_else(|| Vec::with_capacity(self.buffer_init_cap));
48+
debug_assert_eq!(buf.len(), 0);
4449
PooledBuf(buf, self.clone())
4550
}
4651

@@ -51,15 +56,12 @@ impl BufferPool {
5156
}
5257

5358
fn put(self: &Arc<Self>, mut buf: Vec<u8>) {
54-
if buf.len() > self.buffer_cap {
55-
// TODO: until `Vec::shrink_to` stabilization
56-
57-
// SAFETY:
58-
// 1. OK – new_len <= capacity
59-
// 2. OK - 0..new_len is initialized
60-
unsafe { buf.set_len(self.buffer_cap) }
61-
buf.shrink_to_fit();
62-
}
59+
// SAFETY:
60+
// 1. OK – 0 is always within capacity
61+
// 2. OK - nothing to initialize
62+
unsafe { buf.set_len(0) }
63+
64+
buf.shrink_to(self.buffer_size_cap);
6365

6466
// ArrayQueue will make sure to drop the buffer if capacity is exceeded
6567
let _ = self.pool.push(buf);

0 commit comments

Comments
 (0)