Skip to main content

externally_driven_async_rt/storage/
mod.rs

1use core::cell::RefCell;
2
3use crate::{
4    context::Context, io::IoWaiters, notify::Notification, selector::Selector, state::State,
5    tasks::Tasks, time::Timers,
6};
7
8/// The main pre-allocated storage that [`EventLoop`](crate::EventLoop) needs.
9///
10/// A storage can be used by only one [`EventLoop`](crate::EventLoop) ever.
11#[must_use]
12pub struct LoopStorage<
13    const TASKS: usize,
14    const TASK_SIZE: usize,
15    const ROOT_TASK_SIZE: usize,
16    const TIMERS: usize,
17    const FDS: usize,
18> {
19    pub(crate) timers: Timers<TIMERS>,
20    pub(crate) io_waiters: IoWaiters<FDS>,
21    pub(crate) tasks: Tasks<TASKS, TASK_SIZE, ROOT_TASK_SIZE>,
22    pub(crate) notification: Notification,
23}
24
25// SAFETY: a storage has no public methods, so other threads can only pass `&LoopStorage` around.
26// The crate touches it only through a `Context`, which only `Context::claim`
27// creates, and that succeeds once ever, on the thread that runs the claiming loop (claiming the
28// tasks claims their `WakeQueue`, which panics the second time); `EventLoop` and `Context` are
29// `!Send`, so everything but the wakers stays on that thread, and wakers only touch the atomic
30// `WakeQueue`, which asserts that thread.
31unsafe impl<
32    const TASKS: usize,
33    const TASK_SIZE: usize,
34    const ROOT_TASK_SIZE: usize,
35    const TIMERS: usize,
36    const FDS: usize,
37> Sync for LoopStorage<TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
38{
39}
40
41impl<
42    const TASKS: usize,
43    const TASK_SIZE: usize,
44    const ROOT_TASK_SIZE: usize,
45    const TIMERS: usize,
46    const FDS: usize,
47> LoopStorage<TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
48{
49    /// Constructor of an empty storage, **can be called in const-context**, so you can put it into a static variable.
50    pub const fn new() -> Self {
51        Self {
52            timers: Timers::new(),
53            io_waiters: IoWaiters::new(),
54            tasks: Tasks::new(),
55            notification: Notification::new(),
56        }
57    }
58
59    pub(crate) fn claim<'a, S: State>(
60        &'static self,
61        selector: &'a Selector,
62        state: &'a RefCell<S>,
63    ) -> Context<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS> {
64        Context::claim(self, selector, state)
65    }
66}
67
68impl<
69    const TASKS: usize,
70    const TASK_SIZE: usize,
71    const ROOT_TASK_SIZE: usize,
72    const TIMERS: usize,
73    const FDS: usize,
74> core::fmt::Debug for LoopStorage<TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
75{
76    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
77        f.write_str("LoopStorage")
78    }
79}
80
81#[cfg(test)]
82mod tests;