job_pool/
config.rs

1use crate::Result;
2
3/// Pool Config
4///
5/// Configuration for the [ThreadPool](crate::ThreadPool)
6#[derive(Clone,Copy,Debug)]
7pub struct PoolConfig {
8    pub n_workers: u16,
9    pub max_jobs: Option<u16>,
10    pub incoming_buf_size: Option<u16>,
11}
12
13impl PoolConfig {
14    pub const fn builder() -> PoolConfigBuilder {
15        PoolConfigBuilder {
16            n_workers: 16,
17            max_jobs: None,
18            incoming_buf_size: None,
19        }
20    }
21
22    pub fn validate(&self) -> Result<()> {
23        if self.n_workers == 0 {
24            return Err("Invalid pool size: 0".into());
25        }
26        if let Some(max) = self.max_jobs {
27            if max < self.n_workers {
28                return Err(format!("Max number of jobs ({max}) is lower \
29                        than the number of workers ({})", self.n_workers).into())
30            }
31        }
32        Ok(())
33    }
34}
35
36impl Default for PoolConfig {
37    /// Default configuration
38    ///
39    /// NÂș Workers: 16
40    /// Max Jobs: None
41    /// Incoming buf size: None
42    fn default() -> Self {
43        PoolConfig::builder().build()
44    }
45}
46
47pub struct PoolConfigBuilder {
48    n_workers: u16,
49    max_jobs: Option<u16>,
50    incoming_buf_size: Option<u16>,
51}
52
53impl PoolConfigBuilder {
54    pub const fn n_workers(mut self, n: u16) -> Self {
55        self.n_workers = n;
56        self
57    }
58    pub const fn set_n_workers(&mut self, n: u16) -> &mut Self {
59        self.n_workers = n;
60        self
61    }
62    pub const fn max_jobs(mut self, n: u16) -> Self {
63        self.max_jobs = Some(n);
64        self
65    }
66    pub const fn set_max_jobs(&mut self, n: u16) -> &mut Self {
67        self.max_jobs = Some(n);
68        self
69    }
70    pub const fn incoming_buf_size(mut self, n: u16) -> Self {
71        self.incoming_buf_size = Some(n);
72        self
73    }
74    pub const fn set_incoming_buf_size(&mut self, n: u16) -> &mut Self {
75        self.incoming_buf_size = Some(n);
76        self
77    }
78    pub const fn build(self) -> PoolConfig {
79        PoolConfig {
80            n_workers: self.n_workers,
81            incoming_buf_size: self.incoming_buf_size,
82            max_jobs: self.max_jobs,
83        }
84    }
85}