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 const 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_or_else(|e| e.into_inner());
26        pool.pop_front().map_or_else(
27            || vec![T::default(); size],
28            |mut buffer| {
29                buffer.resize(size, T::default());
30                buffer
31            },
32        )
33    }
34
35    /// Return a buffer to the pool
36    pub fn put(&self, buffer: Vec<T>) {
37        let mut pool = self.pool.lock().unwrap_or_else(|e| e.into_inner());
38        pool.push_back(buffer);
39    }
40
41    /// Clear all buffers in the pool
42    pub fn clear(&self) {
43        let mut pool = self.pool.lock().unwrap_or_else(|e| e.into_inner());
44        pool.clear();
45    }
46}
47
48impl<T> Default for BufferPool<T> {
49    fn default() -> Self {
50        Self {
51            pool: Mutex::new(VecDeque::new()),
52            _phantom: PhantomData,
53        }
54    }
55}