1use crate::{DefaultPool, LocalBoxFuture, Park, Pool, Task, TaskHandle};
2use alloc::{boxed::Box, rc::Rc, sync::Arc};
3use core::future::Future;
4
5pub struct Executor<P: Pool = DefaultPool> {
8 pool: Rc<P>,
9 park: Arc<P::Park>,
10}
11impl<P: Pool> Clone for Executor<P> {
12 fn clone(&self) -> Self {
13 Self {
14 pool: self.pool.clone(),
15 park: self.park.clone(),
16 }
17 }
18}
19impl Default for Executor {
20 fn default() -> Self {
21 Self::new(DefaultPool::default())
22 }
23}
24impl<P: Pool> Executor<P> {
25 pub fn new(pool: P) -> Self {
26 Self {
27 pool: Rc::new(pool),
28 park: Arc::new(P::Park::default()),
29 }
30 }
31 pub fn spawn_future(&self, future: LocalBoxFuture<'static>) -> TaskHandle {
32 self.spawn_future_with_priority(0, future)
33 }
34 pub fn spawn_boxed(&self, future: impl Future<Output = ()> + 'static) -> TaskHandle {
35 self.spawn(0, future)
36 }
37 pub fn spawn(&self, priority: u16, future: impl Future<Output = ()> + 'static) -> TaskHandle {
38 self.spawn_future_with_priority(priority, Box::pin(future))
39 }
40 pub fn spawn_future_with_priority(
41 &self,
42 priority: u16,
43 future: LocalBoxFuture<'static>,
44 ) -> TaskHandle {
45 let (task, handle) = Task::new(future, priority, self.park.clone());
46 self.pool.push(task);
47 self.park.unpark();
48 handle
49 }
50 pub fn poll_once(&self) -> bool {
52 let Some(mut task) = self.pool.take_ready() else {
53 return false;
54 };
55 if task.poll().is_pending() {
56 self.pool.push(task);
57 }
58 true
59 }
60 pub fn run_until_stalled(&self) {
62 while self.poll_once() {}
63 }
64 pub fn is_empty(&self) -> bool {
65 self.pool.is_empty()
66 }
67 pub fn run(&self) -> ! {
69 loop {
70 if !self.poll_once() {
71 self.park.park();
72 }
73 }
74 }
75}