Skip to main content

externally_driven_async_rt/tasks/
reserve_task.rs

1use core::{future::Future, pin::Pin, task::Poll};
2
3use crate::{state::State, storage::LoopStorageGuard, tasks::TaskReservation};
4
5/// A future to obtain a [`TaskReservation`].
6#[must_use = "futures do nothing unless you `.await` or poll them"]
7pub struct ReserveTask<
8    'a,
9    S: State,
10    const TASKS: usize,
11    const TASK_SIZE: usize,
12    const ROOT_TASK_SIZE: usize,
13    const TIMERS: usize,
14    const FDS: usize,
15> {
16    storage: LoopStorageGuard<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
17    waiting: bool,
18}
19
20impl<
21    'a,
22    S: State,
23    const TASKS: usize,
24    const TASK_SIZE: usize,
25    const ROOT_TASK_SIZE: usize,
26    const TIMERS: usize,
27    const FDS: usize,
28> ReserveTask<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
29{
30    pub(crate) fn new(
31        storage: LoopStorageGuard<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
32    ) -> Self {
33        Self {
34            storage,
35            waiting: false,
36        }
37    }
38}
39
40impl<
41    'a,
42    S: State,
43    const TASKS: usize,
44    const TASK_SIZE: usize,
45    const ROOT_TASK_SIZE: usize,
46    const TIMERS: usize,
47    const FDS: usize,
48> Future for ReserveTask<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
49{
50    type Output = TaskReservation<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>;
51
52    fn poll(self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
53        let this = self.get_mut();
54        let tasks = this.storage.tasks();
55        match tasks.reserve() {
56            Some(id) => {
57                if this.waiting {
58                    tasks.clear_slot_waiter();
59                    this.waiting = false;
60                }
61                Poll::Ready(TaskReservation::new(this.storage, id))
62            }
63            None => {
64                assert!(
65                    this.waiting || !tasks.has_slot_waiter(),
66                    "only one task can wait for a free task slot"
67                );
68                tasks.set_slot_waiter(cx.waker());
69                this.waiting = true;
70                Poll::Pending
71            }
72        }
73    }
74}
75
76impl<
77    S: State,
78    const TASKS: usize,
79    const TASK_SIZE: usize,
80    const ROOT_TASK_SIZE: usize,
81    const TIMERS: usize,
82    const FDS: usize,
83> Drop for ReserveTask<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
84{
85    fn drop(&mut self) {
86        if self.waiting {
87            self.storage.tasks().clear_slot_waiter();
88        }
89    }
90}
91
92impl<
93    'a,
94    S: State,
95    const TASKS: usize,
96    const TASK_SIZE: usize,
97    const ROOT_TASK_SIZE: usize,
98    const TIMERS: usize,
99    const FDS: usize,
100> core::fmt::Debug for ReserveTask<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
101{
102    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
103        f.write_str("ReserveTask")
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use core::{future::pending, time::Duration};
110
111    use crate::{
112        Selector,
113        testing::{EventLoopTestingExt, Log, TEST_TASKS, TestLoop, TestStorage},
114    };
115
116    #[test]
117    #[cfg_attr(miri, ignore)]
118    fn waits_until_a_task_finishes() {
119        let mut selector = Selector::new().unwrap();
120        let mut event_loop = TestLoop::new(
121            {
122                static STORAGE: TestStorage = TestStorage::new();
123                &STORAGE
124            },
125            &mut selector,
126            Log::default(),
127            async |ctx| {
128                ctx.spawn(async |ctx| {
129                    ctx.sleep(Duration::from_millis(10)).await;
130                    ctx.dispatch(1);
131                });
132                for _ in 0..TEST_TASKS - 2 {
133                    ctx.spawn(async |_| pending::<()>().await);
134                }
135                let _task = ctx.reserve_task().await;
136                ctx.dispatch(2);
137                pending::<()>().await;
138            },
139        )
140        .unwrap();
141        assert!(event_loop.state_mut().events().is_empty());
142        event_loop.run_until_events(2);
143        assert_eq!(event_loop.state_mut().events(), [1, 2]);
144    }
145
146    #[test]
147    #[cfg_attr(miri, ignore)]
148    #[should_panic(expected = "only one task can wait for a free task slot")]
149    fn a_second_waiter_panics() {
150        let mut selector = Selector::new().unwrap();
151        let _ = TestLoop::new(
152            {
153                static STORAGE: TestStorage = TestStorage::new();
154                &STORAGE
155            },
156            &mut selector,
157            Log::default(),
158            async |ctx| {
159                for _ in 0..TEST_TASKS - 3 {
160                    ctx.spawn(async |_| pending::<()>().await);
161                }
162                for _ in 0..2 {
163                    ctx.spawn(async |ctx| {
164                        let _task = ctx.reserve_task().await;
165                    });
166                }
167                pending::<()>().await;
168            },
169        );
170    }
171}