concurrent_pool/builder.rs
1use crate::{Config, Pool};
2
3/// A builder for creating a [`Pool`] with custom configuration.
4///
5/// # Example
6///
7/// ```rust
8/// use concurrent_pool::Builder;
9///
10/// let mut builder = Builder::<usize>::new();
11/// let pool = builder.capacity(10).prealloc(5).build();
12/// assert_eq!(pool.capacity(), 10);
13/// ```
14pub struct Builder<T: Default> {
15 /// Configuration of the pool.
16 config: Config<T>,
17}
18
19impl<T: Default> Builder<T> {
20 /// Create a new builder with default configuration.
21 pub fn new() -> Self {
22 Self {
23 config: Config::default(),
24 }
25 }
26
27 /// Set the number of preallocated items in the pool.
28 pub fn prealloc(&mut self, prealloc: usize) -> &mut Self {
29 self.config.prealloc = prealloc;
30 self
31 }
32
33 /// Set the maximum capacity of the pool.
34 pub fn capacity(&mut self, capacity: usize) -> &mut Self {
35 self.config.capacity = capacity;
36 self
37 }
38
39 /// Set the function to clear an item before it is returned to the pool.
40 pub fn clear_func(&mut self, func: fn(&mut T)) -> &mut Self {
41 self.config.clear_func = Some(func);
42 self
43 }
44
45 /// Enable or disable auto reclaiming allocated items and free them to reduce memory usage.
46 pub fn auto_reclaim(&mut self, enable: bool) -> &mut Self {
47 self.config.auto_reclaim = enable;
48 self
49 }
50
51 /// Enable auto reclaiming allocated items and free them to reduce memory usage.
52 pub fn enable_auto_reclaim(&mut self) -> &mut Self {
53 self.auto_reclaim(true)
54 }
55
56 /// Set the threshold of `surplus-pull` continuous occurrence to trigger reclamation
57 /// when `auto_reclaim` is enabled.
58 pub fn surpluspull_threshold_for_reclaim(&mut self, threshold: usize) -> &mut Self {
59 self.config.surpluspull_threshold_for_reclaim = threshold;
60 self
61 }
62
63 /// Set the threshold for idle items to judge as a `surplus-pull` when `auto_reclaim` is enabled.
64 pub fn idle_threshold_for_surpluspull(&mut self, threshold: usize) -> &mut Self {
65 self.config.idle_threshold_for_surpluspull = threshold;
66 self
67 }
68
69 /// Build the pool with the current configuration.
70 pub fn build(&mut self) -> Pool<T> {
71 let config = std::mem::take(&mut self.config);
72 Pool::with_config(config)
73 }
74}