lockfree_object_pool/none_object_pool.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
use crate::none_reusable::NoneReusable;
use std::sync::Arc;
/// Basic allocation without pull. Used to compare default rust allocation with different kind of object pool.
/// # Example
/// ```rust
/// use lockfree_object_pool::NoneObjectPool;
///
/// let pool = NoneObjectPool::<u32>::new(|| Default::default());
/// let mut item = pool.pull();
///
/// *item = 5;
/// let work = *item * 5;
/// ```
pub struct NoneObjectPool<T> {
init: Box<dyn Fn() -> T + Send + Sync>,
}
impl<T> NoneObjectPool<T> {
///
/// Create an new [`NoneObjectPool`]
///
/// # Arguments
/// * `init` closure to create new item
///
/// # Example
/// ```rust
/// use lockfree_object_pool::NoneObjectPool;
///
/// let pool = NoneObjectPool::<u32>::new(|| Default::default());
/// ```
#[inline]
pub fn new<I>(init: I) -> Self
where
I: Fn() -> T + Send + Sync + 'static,
{
Self {
init: Box::new(init),
}
}
///
/// Create a new element. When the element is dropped, it doesn't return in the pull.
///
/// # Example
/// ```rust
/// use lockfree_object_pool::NoneObjectPool;
///
/// let pool = NoneObjectPool::<u32>::new(|| Default::default());
/// let mut item = pool.pull();
/// ```
#[inline]
pub fn pull(&self) -> NoneReusable<T> {
NoneReusable::new((self.init)())
}
///
/// Create a new element. When the element is dropped, it doesn't return in the pull.
///
/// # Example
/// ```rust
/// use std::sync::Arc;
/// use lockfree_object_pool::NoneObjectPool;
///
/// let pool = Arc::new(NoneObjectPool::<u32>::new(|| Default::default()));
/// let mut item = pool.pull_owned();
/// ```
#[inline]
pub fn pull_owned(self: &Arc<Self>) -> NoneReusable<T> {
NoneReusable::new((self.init)())
}
}