rat_salsa/poll/
thread_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
use crate::thread_pool::ThreadPool;
use crate::{Control, PollEvents};
use crossbeam::channel::TryRecvError;
use std::any::Any;
use std::rc::Rc;

/// Processes results from background tasks.
#[derive(Debug)]
pub struct PollTasks<Event, Error>
where
    Event: 'static + Send,
    Error: 'static + Send,
{
    tasks: Rc<ThreadPool<Event, Error>>,
}

impl<Event, Error> Default for PollTasks<Event, Error>
where
    Event: 'static + Send,
    Error: 'static + Send,
{
    fn default() -> Self {
        Self::new(1)
    }
}

impl<Event, Error> PollTasks<Event, Error>
where
    Event: 'static + Send,
    Error: 'static + Send,
{
    pub fn new(num_workers: usize) -> Self {
        Self {
            tasks: Rc::new(ThreadPool::new(num_workers)),
        }
    }

    pub(crate) fn get_tasks(&self) -> Rc<ThreadPool<Event, Error>> {
        self.tasks.clone()
    }
}

impl<Event, Error> PollEvents<Event, Error> for PollTasks<Event, Error>
where
    Event: 'static + Send,
    Error: 'static + Send + From<TryRecvError>,
{
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn poll(&mut self) -> Result<bool, Error> {
        Ok(!self.tasks.is_empty())
    }

    fn read(&mut self) -> Result<Control<Event>, Error> {
        self.tasks.try_recv()
    }
}