Skip to main content

rabia_core/
memory_pool.rs

1use bytes::Bytes;
2use std::collections::VecDeque;
3use std::sync::{Arc, Mutex};
4
5/// A simple memory pool for reusing byte buffers to reduce allocations
6pub struct MemoryPool {
7    small_buffers: Arc<Mutex<VecDeque<Vec<u8>>>>,
8    medium_buffers: Arc<Mutex<VecDeque<Vec<u8>>>>,
9    large_buffers: Arc<Mutex<VecDeque<Vec<u8>>>>,
10    max_pool_size: usize,
11}
12
13#[derive(Debug, Clone)]
14pub struct PoolConfig {
15    pub small_buffer_size: usize,
16    pub medium_buffer_size: usize,
17    pub large_buffer_size: usize,
18    pub max_pool_size: usize,
19}
20
21impl Default for PoolConfig {
22    fn default() -> Self {
23        Self {
24            small_buffer_size: 1024,  // 1KB for typical messages
25            medium_buffer_size: 8192, // 8KB for batch messages
26            large_buffer_size: 65536, // 64KB for large batches
27            max_pool_size: 100,       // Max pooled buffers per size
28        }
29    }
30}
31
32impl MemoryPool {
33    pub fn new(config: PoolConfig) -> Self {
34        Self {
35            small_buffers: Arc::new(Mutex::new(VecDeque::with_capacity(config.max_pool_size))),
36            medium_buffers: Arc::new(Mutex::new(VecDeque::with_capacity(config.max_pool_size))),
37            large_buffers: Arc::new(Mutex::new(VecDeque::with_capacity(config.max_pool_size))),
38            max_pool_size: config.max_pool_size,
39        }
40    }
41
42    /// Get a buffer of appropriate size from the pool
43    pub fn get_buffer(&self, min_size: usize) -> PooledBuffer {
44        let (buffer, pool, original_capacity) = if min_size <= 1024 {
45            let mut pool = self.small_buffers.lock().unwrap();
46            let buffer = pool.pop_front().unwrap_or_else(|| Vec::with_capacity(1024));
47            (buffer, self.small_buffers.clone(), 1024)
48        } else if min_size <= 8192 {
49            let mut pool = self.medium_buffers.lock().unwrap();
50            let buffer = pool.pop_front().unwrap_or_else(|| Vec::with_capacity(8192));
51            (buffer, self.medium_buffers.clone(), 8192)
52        } else {
53            let mut pool = self.large_buffers.lock().unwrap();
54            let buffer = pool
55                .pop_front()
56                .unwrap_or_else(|| Vec::with_capacity(65536.max(min_size)));
57            (buffer, self.large_buffers.clone(), 65536.max(min_size))
58        };
59
60        PooledBuffer {
61            buffer,
62            pool,
63            original_capacity,
64            max_pool_size: self.max_pool_size,
65        }
66    }
67
68    /// Pre-warm the pool with buffers
69    pub fn warm_up(&self) {
70        let config = PoolConfig::default();
71
72        // Pre-allocate some buffers
73        for _ in 0..10 {
74            self.small_buffers
75                .lock()
76                .unwrap()
77                .push_back(Vec::with_capacity(config.small_buffer_size));
78            self.medium_buffers
79                .lock()
80                .unwrap()
81                .push_back(Vec::with_capacity(config.medium_buffer_size));
82            self.large_buffers
83                .lock()
84                .unwrap()
85                .push_back(Vec::with_capacity(config.large_buffer_size));
86        }
87    }
88
89    /// Get statistics about pool usage
90    pub fn stats(&self) -> PoolStats {
91        PoolStats {
92            small_buffers_available: self.small_buffers.lock().unwrap().len(),
93            medium_buffers_available: self.medium_buffers.lock().unwrap().len(),
94            large_buffers_available: self.large_buffers.lock().unwrap().len(),
95        }
96    }
97
98    /// Clear all pooled buffers
99    pub fn clear(&self) {
100        self.small_buffers.lock().unwrap().clear();
101        self.medium_buffers.lock().unwrap().clear();
102        self.large_buffers.lock().unwrap().clear();
103    }
104}
105
106impl Default for MemoryPool {
107    fn default() -> Self {
108        Self::new(PoolConfig::default())
109    }
110}
111
112/// A buffer that returns to the pool when dropped
113pub struct PooledBuffer {
114    buffer: Vec<u8>,
115    pool: Arc<Mutex<VecDeque<Vec<u8>>>>,
116    original_capacity: usize,
117    max_pool_size: usize,
118}
119
120impl PooledBuffer {
121    /// Get the underlying buffer
122    pub fn buffer_mut(&mut self) -> &mut Vec<u8> {
123        &mut self.buffer
124    }
125
126    /// Take ownership of the buffer contents as Bytes
127    pub fn take_bytes(&mut self) -> Bytes {
128        Bytes::from(std::mem::take(&mut self.buffer))
129    }
130
131    /// Get a reference to the buffer
132    pub fn as_slice(&self) -> &[u8] {
133        &self.buffer
134    }
135
136    /// Get the length of the buffer
137    pub fn len(&self) -> usize {
138        self.buffer.len()
139    }
140
141    /// Check if the buffer is empty
142    pub fn is_empty(&self) -> bool {
143        self.buffer.is_empty()
144    }
145
146    /// Resize the buffer
147    pub fn resize(&mut self, new_len: usize, value: u8) {
148        self.buffer.resize(new_len, value);
149    }
150
151    /// Clear the buffer content but keep capacity
152    pub fn clear(&mut self) {
153        self.buffer.clear();
154    }
155}
156
157impl Drop for PooledBuffer {
158    fn drop(&mut self) {
159        // Clear the buffer but keep capacity
160        self.buffer.clear();
161
162        // Only return to pool if it's the right size and pool isn't full
163        if self.buffer.capacity() == self.original_capacity {
164            let mut pool = self.pool.lock().unwrap();
165            if pool.len() < self.max_pool_size {
166                pool.push_back(std::mem::take(&mut self.buffer));
167            }
168        }
169    }
170}
171
172#[derive(Debug)]
173pub struct PoolStats {
174    pub small_buffers_available: usize,
175    pub medium_buffers_available: usize,
176    pub large_buffers_available: usize,
177}
178
179// Thread-local memory pool for high-performance scenarios
180thread_local! {
181    static LOCAL_POOL: MemoryPool = {
182        let pool = MemoryPool::default();
183        pool.warm_up();
184        pool
185    };
186}
187
188/// Get a buffer from the thread-local pool
189pub fn get_pooled_buffer(min_size: usize) -> PooledBuffer {
190    LOCAL_POOL.with(|pool| pool.get_buffer(min_size))
191}
192
193/// Optimized string pool for command strings
194pub struct StringPool {
195    small_strings: Arc<Mutex<VecDeque<String>>>,
196    large_strings: Arc<Mutex<VecDeque<String>>>,
197    max_pool_size: usize,
198}
199
200impl StringPool {
201    pub fn new(max_pool_size: usize) -> Self {
202        Self {
203            small_strings: Arc::new(Mutex::new(VecDeque::with_capacity(max_pool_size))),
204            large_strings: Arc::new(Mutex::new(VecDeque::with_capacity(max_pool_size))),
205            max_pool_size,
206        }
207    }
208
209    pub fn get_string(&self, min_capacity: usize) -> PooledString {
210        let (string, pool, is_large) = if min_capacity <= 256 {
211            let mut pool = self.small_strings.lock().unwrap();
212            let string = pool
213                .pop_front()
214                .unwrap_or_else(|| String::with_capacity(256));
215            (string, self.small_strings.clone(), false)
216        } else {
217            let mut pool = self.large_strings.lock().unwrap();
218            let string = pool
219                .pop_front()
220                .unwrap_or_else(|| String::with_capacity(1024.max(min_capacity)));
221            (string, self.large_strings.clone(), true)
222        };
223
224        PooledString {
225            string,
226            pool,
227            is_large,
228            max_pool_size: self.max_pool_size,
229        }
230    }
231}
232
233impl Default for StringPool {
234    fn default() -> Self {
235        Self::new(50)
236    }
237}
238
239pub struct PooledString {
240    string: String,
241    pool: Arc<Mutex<VecDeque<String>>>,
242    #[allow(dead_code)]
243    is_large: bool,
244    max_pool_size: usize,
245}
246
247impl PooledString {
248    pub fn as_str(&self) -> &str {
249        &self.string
250    }
251
252    pub fn push_str(&mut self, s: &str) {
253        self.string.push_str(s);
254    }
255
256    pub fn clear(&mut self) {
257        self.string.clear();
258    }
259
260    pub fn into_string(mut self) -> String {
261        // Prevent drop from returning to pool
262        let mut string = String::new();
263        std::mem::swap(&mut string, &mut self.string);
264        std::mem::forget(self);
265        string
266    }
267}
268
269impl Drop for PooledString {
270    fn drop(&mut self) {
271        self.string.clear();
272        let mut pool = self.pool.lock().unwrap();
273        if pool.len() < self.max_pool_size {
274            pool.push_back(std::mem::take(&mut self.string));
275        }
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    #[test]
284    fn test_memory_pool_basic() {
285        let pool = MemoryPool::default();
286
287        let mut buffer = pool.get_buffer(100);
288        buffer.buffer_mut().extend_from_slice(b"hello world");
289        assert_eq!(buffer.len(), 11);
290
291        // Drop the buffer, should return to pool
292        drop(buffer);
293
294        // Get another buffer, should reuse the previous one
295        let stats = pool.stats();
296        assert!(stats.small_buffers_available > 0);
297    }
298
299    #[test]
300    fn test_different_buffer_sizes() {
301        let pool = MemoryPool::default();
302
303        let small = pool.get_buffer(500); // Should use small pool
304        let medium = pool.get_buffer(4000); // Should use medium pool
305        let large = pool.get_buffer(32000); // Should use large pool
306
307        assert!(small.buffer.capacity() >= 500);
308        assert!(medium.buffer.capacity() >= 4000);
309        assert!(large.buffer.capacity() >= 32000);
310    }
311
312    #[test]
313    fn test_thread_local_pool() {
314        let buffer1 = get_pooled_buffer(100);
315        let buffer2 = get_pooled_buffer(200);
316
317        assert!(buffer1.buffer.capacity() >= 100);
318        assert!(buffer2.buffer.capacity() >= 200);
319    }
320
321    #[test]
322    fn test_string_pool() {
323        let pool = StringPool::default();
324
325        let mut string = pool.get_string(100);
326        string.push_str("hello");
327        string.push_str(" world");
328
329        assert_eq!(string.as_str(), "hello world");
330
331        // Test conversion to owned string
332        let owned = string.into_string();
333        assert_eq!(owned, "hello world");
334    }
335
336    #[test]
337    fn test_pooled_buffer_bytes() {
338        let pool = MemoryPool::default();
339        let mut buffer = pool.get_buffer(100);
340
341        buffer.buffer_mut().extend_from_slice(b"test data");
342        let bytes = buffer.take_bytes();
343
344        assert_eq!(bytes.as_ref(), b"test data");
345        assert_eq!(buffer.len(), 0); // Buffer should be empty after taking bytes
346    }
347}