block_pool/
lib.rs

1//! A simple object pool that blocks when taking an item out.
2//!
3//! ```
4//! use block_pool::Pool;
5//!
6//! let pool = Pool::new(vec![1, 2, 3]);
7//! let mut item = pool.take();
8//! *item += 1;
9//! drop(item);
10//! ```
11
12use std::{
13    collections::VecDeque,
14    ops::{Deref, DerefMut},
15    sync::{Condvar, Mutex},
16};
17
18/// Container for objects that can be taken out.
19pub struct Pool<T> {
20    items: Mutex<VecDeque<T>>,
21    value_returned: Condvar,
22}
23
24impl<T> Pool<T> {
25    /// Construct a new Pool with the items from the iterator.
26    pub fn new(items: impl IntoIterator<Item = T>) -> Self {
27        Pool {
28            items: Mutex::new(items.into_iter().collect()),
29            value_returned: Condvar::new(),
30        }
31    }
32
33    /// Remove an item from the pool, this will take the "oldest" item.
34    ///
35    /// The item will automatically get returned to the pool when the smart pointer is dropped.
36    ///
37    /// There is no "resetting" that is common in other frameworks. You need to perform any
38    /// resetting on your own.
39    pub fn take(&self) -> Returnable<T> {
40        let mut lock = self.items.lock().unwrap();
41        loop {
42            if let Some(value) = lock.pop_front() {
43                return Returnable {
44                    value: Some(value),
45                    pool: self,
46                };
47            }
48            lock = self.value_returned.wait(lock).unwrap();
49        }
50    }
51
52    fn return_(&self, value: T) {
53        self.items.lock().unwrap().push_back(value);
54    }
55}
56
57/// A smart pointer that holds an object taken from a pool.
58///
59/// Returns the object to the pool when dropped.
60pub struct Returnable<'p, T> {
61    // Only Option so that we can take ownership of the value in Drop.
62    value: Option<T>,
63    pool: &'p Pool<T>,
64}
65
66impl<'p, T> Drop for Returnable<'p, T> {
67    fn drop(&mut self) {
68        self.pool.return_(self.value.take().unwrap());
69        self.pool.value_returned.notify_one();
70    }
71}
72
73impl<'p, T> Deref for Returnable<'p, T> {
74    type Target = T;
75
76    fn deref(&self) -> &Self::Target {
77        self.value.as_ref().unwrap()
78    }
79}
80
81impl<'p, T> DerefMut for Returnable<'p, T> {
82    fn deref_mut(&mut self) -> &mut Self::Target {
83        self.value.as_mut().unwrap()
84    }
85}