Skip to main content

externally_driven_async_rt/storage/
mod.rs

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