Skip to main content

externally_driven_async_rt/storage/
mod.rs

1use core::cell::RefCell;
2
3use crate::{
4    context::Context, io::IoWaiters, selector::Selector, state::State, tasks::Tasks, time::Timers,
5};
6
7/// The main pre-allocated storage that [`EventLoop`](crate::EventLoop) needs.
8///
9/// A storage can be used by only one [`EventLoop`](crate::EventLoop) ever.
10#[must_use]
11pub struct LoopStorage<
12    const TASKS: usize,
13    const TASK_SIZE: usize,
14    const ROOT_TASK_SIZE: usize,
15    const TIMERS: usize,
16    const FDS: usize,
17> {
18    pub(crate) timers: Timers<TIMERS>,
19    pub(crate) io_waiters: IoWaiters<FDS>,
20    pub(crate) 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 `Context`, which only `Context::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    const TASKS: usize,
31    const TASK_SIZE: usize,
32    const ROOT_TASK_SIZE: usize,
33    const TIMERS: usize,
34    const FDS: usize,
35> Sync for LoopStorage<TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
36{
37}
38
39impl<
40    const TASKS: usize,
41    const TASK_SIZE: usize,
42    const ROOT_TASK_SIZE: usize,
43    const TIMERS: usize,
44    const FDS: usize,
45> LoopStorage<TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
46{
47    /// Constructor of an empty storage, **can be called in const-context**, so you can put it into a static variable.
48    pub const fn new() -> Self {
49        Self {
50            timers: Timers::new(),
51            io_waiters: IoWaiters::new(),
52            tasks: Tasks::new(),
53        }
54    }
55
56    pub(crate) fn claim<'a, S: State>(
57        &'static self,
58        selector: &'a Selector,
59        state: &'a RefCell<S>,
60    ) -> Context<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS> {
61        Context::claim(self, selector, state)
62    }
63}
64
65impl<
66    const TASKS: usize,
67    const TASK_SIZE: usize,
68    const ROOT_TASK_SIZE: usize,
69    const TIMERS: usize,
70    const FDS: usize,
71> core::fmt::Debug for LoopStorage<TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
72{
73    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
74        f.write_str("LoopStorage")
75    }
76}
77
78#[cfg(test)]
79mod tests;