lockfree_object_pool/
mutex_owned_reusable.rs

1use crate::mutex_object_pool::MutexObjectPool;
2use std::mem::ManuallyDrop;
3use std::ops::{Deref, DerefMut};
4use std::sync::Arc;
5
6/// Wrapper over T used by [`MutexObjectPool`].
7///
8/// Access is allowed with [`std::ops::Deref`] or [`std::ops::DerefMut`]
9/// # Example
10/// ```rust
11///  use lockfree_object_pool::MutexObjectPool;
12///  use std::sync::Arc;
13///
14///  let pool = Arc::new(MutexObjectPool::<u32>::new(
15///    ||  Default::default(),
16///    |v| {
17///      *v = 0;
18///    }
19///  ));
20///  let mut item = pool.pull_owned();
21///
22///  *item = 5;
23///  let work = *item * 5;
24/// ```
25pub struct MutexOwnedReusable<T> {
26    pool: Arc<MutexObjectPool<T>>,
27    data: ManuallyDrop<T>,
28}
29
30impl<T> MutexOwnedReusable<T> {
31    /// Create new element
32    ///
33    /// # Arguments
34    /// * `pool` object pool owner
35    /// * `data` element to wrap
36    #[inline]
37    pub fn new(pool: Arc<MutexObjectPool<T>>, data: ManuallyDrop<T>) -> Self {
38        Self { pool, data }
39    }
40}
41
42impl<T> DerefMut for MutexOwnedReusable<T> {
43    #[inline]
44    fn deref_mut(&mut self) -> &mut Self::Target {
45        &mut self.data
46    }
47}
48
49impl<T> Deref for MutexOwnedReusable<T> {
50    type Target = T;
51
52    #[inline]
53    fn deref(&self) -> &Self::Target {
54        &self.data
55    }
56}
57
58impl<T> Drop for MutexOwnedReusable<T> {
59    #[inline]
60    fn drop(&mut self) {
61        let data = unsafe {
62            // SAFETY: self.data is never referenced again and it isn't dropped
63            ManuallyDrop::take(&mut self.data)
64        };
65        self.pool.attach(data);
66    }
67}