autoreturn_pool/
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
use crate::pool_object::PoolObject;
use crate::Config;
use parking_lot::{Condvar, Mutex};

/// A pool of objects.
/// After an object is taken from the pool, it is returned to the pool when it is dropped.
/// Pool items must be passed on creation by values:
/// # Examples
/// basic usage:
/// ```
/// let pool = autoreturn_pool::Pool::new([1, 2]);
/// let item = pool.take();
/// ```
/// with custom config:
/// ```
/// let config = autoreturn_pool::Config {
///    wait_duration: std::time::Duration::from_millis(5),
/// };
/// let pool = autoreturn_pool::Pool::with_config(config, [1, 2]);
/// let item = pool.take();
/// ```
pub struct Pool<T: Send> {
    config: Config,
    storage: Mutex<Vec<T>>,
    condvar: Condvar,
}

impl<T: Send + 'static> Pool<T> {
    pub fn new(items: impl IntoIterator<Item = T>) -> Self {
        Self::with_config(Config::default(), items)
    }

    pub fn with_config(config: Config, items: impl IntoIterator<Item = T>) -> Self {
        let objects = items.into_iter().collect();
        Self {
            config,
            storage: Mutex::new(objects),
            condvar: Condvar::new(),
        }
    }

    /// Take an object from the pool.
    /// If the pool is empty, the method will wait for the object to be returned to the pool.
    /// If the wait duration is exceeded, the method will return `None`.
    pub fn take(&self) -> Option<PoolObject<T>> {
        let mut lock = self.storage.lock();
        while lock.is_empty() {
            let wait_res = self.condvar.wait_for(&mut lock, self.config.wait_duration);
            if wait_res.timed_out() {
                return None;
            }
        }
        let inner = lock.pop().unwrap();
        Some(PoolObject::new(inner, self))
    }

    /// Allows to add new object to the pool.
    pub fn add(&self, item: T) {
        self.storage.lock().push(item);
    }

    /// Get the number of available objects in the pool.
    pub fn size(&self) -> usize {
        self.storage.lock().len()
    }

    /// Put an object back into the pool and notify one waiting thread.
    pub(crate) fn put(&self, item: T) {
        self.storage.lock().push(item);
        self.condvar.notify_one();
    }
}

#[cfg(test)]
mod tests {
    use crate::pool::Pool;
    use crate::Config;
    use std::ops::Deref;

    #[test]
    fn test_create() {
        let pool = Pool::new([1, 2, 3]);
        assert_eq!(pool.size(), 3);
    }

    #[test]
    fn test_take() {
        let pool = Pool::new([1, 2, 3]);
        let obj1 = pool.take();
        assert_eq!(pool.size(), 2);
        assert_eq!(*obj1.as_ref().unwrap().deref(), 3);
    }

    #[test]
    fn test_add() {
        let pool = Pool::new([1]);
        pool.add(2);
        assert_eq!(pool.size(), 2);
    }

    #[test]
    fn test_wait() {
        let wait_time = std::time::Duration::from_millis(20);
        let config = Config {
            wait_duration: wait_time,
        };
        let pool = Pool::with_config(config, [1]);
        let _obj1 = pool.take();
        assert_eq!(pool.size(), 0);
        let start_time = std::time::Instant::now();
        let obj2 = pool.take();
        assert!(start_time.elapsed() >= wait_time);
        assert!(obj2.is_none());
    }

    #[test]
    fn test_workflow() -> anyhow::Result<()> {
        let config = Config {
            wait_duration: std::time::Duration::from_millis(5),
        };
        let pool = Pool::with_config(config, [1, 2, 3]);
        assert_eq!(pool.size(), 3);

        let obj1 = pool.take();
        assert_eq!(pool.size(), 2);
        assert_eq!(*obj1.as_ref().unwrap().deref(), 3);

        let obj2 = pool.take();
        assert_eq!(*obj2.as_ref().unwrap().deref(), 2);
        let obj3 = pool.take();
        assert_eq!(pool.size(), 0);
        assert_eq!(*obj3.as_ref().unwrap().deref(), 1);

        let obj4 = pool.take();
        assert!(obj4.is_none());

        Ok(())
    }
}