quantrs2_core/
buffer_pool.rs

1//! Temporary BufferPool implementation to replace scirs2_core::memory::BufferPool
2//! TODO: Replace with scirs2_core when regex dependency issue is fixed
3
4use std::collections::VecDeque;
5use std::marker::PhantomData;
6use std::sync::Mutex;
7
8/// A simple buffer pool implementation
9pub struct BufferPool<T> {
10    pool: Mutex<VecDeque<Vec<T>>>,
11    _phantom: PhantomData<T>,
12}
13
14impl<T: Clone + Default> BufferPool<T> {
15    /// Create a new buffer pool
16    pub fn new() -> Self {
17        Self {
18            pool: Mutex::new(VecDeque::new()),
19            _phantom: PhantomData,
20        }
21    }
22
23    /// Get a buffer from the pool
24    pub fn get(&self, size: usize) -> Vec<T> {
25        let mut pool = self.pool.lock().unwrap();
26        if let Some(mut buffer) = pool.pop_front() {
27            buffer.resize(size, T::default());
28            buffer
29        } else {
30            vec![T::default(); size]
31        }
32    }
33
34    /// Return a buffer to the pool
35    pub fn put(&self, buffer: Vec<T>) {
36        let mut pool = self.pool.lock().unwrap();
37        pool.push_back(buffer);
38    }
39
40    /// Clear all buffers in the pool
41    pub fn clear(&self) {
42        let mut pool = self.pool.lock().unwrap();
43        pool.clear();
44    }
45}
46
47impl<T> Default for BufferPool<T> {
48    fn default() -> Self {
49        Self {
50            pool: Mutex::new(VecDeque::new()),
51            _phantom: PhantomData,
52        }
53    }
54}