easy_pool/
pool_array_queue.rs

1use std::{fmt::Debug, sync::Arc};
2
3use crossbeam::queue::ArrayQueue;
4
5use crate::{Clear, PoolObjectContainer, PoolType};
6
7#[derive(Debug)]
8pub struct PoolArrayQueue<T> {
9    pub(crate) values: ArrayQueue<T>,
10    pub(crate) max_size: usize,
11}
12
13impl<T> PoolArrayQueue<T>
14where
15    T: Clear,
16{
17    pub fn new(capacity: usize) -> Self {
18        Self {
19            values: ArrayQueue::new(capacity),
20            max_size: capacity,
21        }
22    }
23
24    /// Create an object (default).
25    #[inline]
26    pub fn create(self: &Arc<Self>) -> PoolObjectContainer<T>
27    where
28        T: Clear + Default,
29    {
30        self.create_with(|| Default::default())
31    }
32
33    /// Create an object.
34    /// The FnOnce that you pass as an argument does not affect the object if it is already present in the pool.
35    /// It is interesting for example when creating a "vector" to specify a capacity.
36    pub fn create_with<F: FnOnce() -> T>(self: &Arc<Self>, f: F) -> PoolObjectContainer<T> {
37        let val = self.values.pop().unwrap_or_else(f);
38        PoolObjectContainer::new(val, PoolType::ArrayQueue(Arc::clone(&self)))
39    }
40
41    #[inline]
42    pub fn len(&self) -> usize {
43        self.values.len()
44    }
45}
46
47impl<T: Clear> Default for PoolArrayQueue<T> {
48    fn default() -> Self {
49        Self::new(1024)
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test() {
59        let pool = Arc::new(PoolArrayQueue::<Vec<u8>>::new(1024));
60        let mut new_vec = pool.create();
61        new_vec.extend_from_slice(&[0, 0, 0, 0, 1, 1]);
62        let capacity = new_vec.capacity();
63        drop(new_vec);
64        assert!(!pool.values.is_empty());
65        let new_vec = pool.create();
66        assert!(new_vec.capacity() > 0 && new_vec.capacity() == capacity);
67        assert!(new_vec.is_empty());
68        assert!(pool.values.is_empty());
69        drop(new_vec);
70    }
71
72    #[test]
73    fn test_create_with() {
74        let pool = Arc::new(PoolArrayQueue::<Vec<u8>>::new(1024));
75        let r = pool.create_with(|| Vec::with_capacity(4096));
76        assert_eq!(r.capacity(), 4096);
77    }
78
79    #[test]
80    fn test_create() {
81        let pool = Arc::new(PoolArrayQueue::<Vec<u8>>::new(1024));
82        let r = pool.create();
83        assert_eq!(r.capacity(), Vec::<u8>::default().capacity());
84    }
85
86    #[test]
87    fn test_len() {
88        let pool = Arc::new(PoolArrayQueue::<Vec<u8>>::new(1024));
89        assert_eq!(pool.len(), 0);
90        let new_vec = pool.create();
91        drop(new_vec);
92        assert_eq!(pool.len(), 1);
93    }
94}