Skip to main content

squawk_thread/
taskpool.rs

1// Taken from:
2// https://github.com/rust-lang/rust-analyzer/blob/2efc80078029894eec0699f62ec8d5c1a56af763/crates/rust-analyzer/src/task_pool.rs#L6C19-L6C19
3//! A thin wrapper around [`crate::Pool`] which threads a sender through spawned jobs.
4
5use std::num::NonZeroUsize;
6
7use crossbeam_channel::Sender;
8
9use crate::{Pool, ThreadIntent};
10
11pub struct TaskPool<T> {
12    sender: Sender<T>,
13    pool: Pool,
14}
15
16impl<T> TaskPool<T> {
17    pub fn new_with_threads(sender: Sender<T>, threads: NonZeroUsize) -> TaskPool<T> {
18        TaskPool {
19            sender,
20            pool: Pool::new(threads),
21        }
22    }
23
24    pub fn spawn<F>(&mut self, intent: ThreadIntent, task: F)
25    where
26        F: FnOnce() -> T + Send + 'static,
27        T: Send + 'static,
28    {
29        self.pool.spawn(intent, {
30            let sender = self.sender.clone();
31            move || sender.send(task()).unwrap()
32        })
33    }
34
35    pub fn spawn_with_sender<F>(&mut self, intent: ThreadIntent, task: F)
36    where
37        F: FnOnce(Sender<T>) + Send + 'static,
38        T: Send + 'static,
39    {
40        self.pool.spawn(intent, {
41            let sender = self.sender.clone();
42            move || task(sender)
43        })
44    }
45
46    pub fn len(&self) -> usize {
47        self.pool.len()
48    }
49
50    pub fn is_empty(&self) -> bool {
51        self.pool.len() == 0
52    }
53}