use crate::{
spin_lock::SpinLock, spin_lock_owned_reusable::SpinLockOwnedReusable,
spin_lock_reusable::SpinLockReusable,
};
use std::mem::ManuallyDrop;
use std::sync::Arc;
pub struct SpinLockObjectPool<T> {
objects: SpinLock<Vec<T>>,
reset: Box<dyn Fn(&mut T) + Send + Sync>,
init: Box<dyn Fn() -> T + Send + Sync>,
}
impl<T> SpinLockObjectPool<T> {
#[inline]
pub fn new<R, I>(init: I, reset: R) -> Self
where
R: Fn(&mut T) + Send + Sync + 'static,
I: Fn() -> T + Send + Sync + 'static,
{
Self {
objects: SpinLock::new(Vec::new()),
reset: Box::new(reset),
init: Box::new(init),
}
}
#[inline]
pub fn pull(&self) -> SpinLockReusable<T> {
SpinLockReusable::new(
self,
ManuallyDrop::new(self.objects.lock().pop().unwrap_or_else(&self.init)),
)
}
#[inline]
pub fn pull_owned(self: &Arc<Self>) -> SpinLockOwnedReusable<T> {
SpinLockOwnedReusable::new(
self.clone(),
ManuallyDrop::new(self.objects.lock().pop().unwrap_or_else(&self.init)),
)
}
#[inline]
pub(crate) fn attach(&self, mut data: T) {
(self.reset)(&mut data);
self.objects.lock().push(data);
}
}