Skip to main content

externally_driven_async_rt/
context.rs

1use core::{future::Future, time::Duration};
2
3use crate::{
4    state::State,
5    storage::LoopStorageGuard,
6    tasks::{JoinHandle, ReserveTask},
7    time::{Instant, Sleep, Timeout},
8};
9
10/// A handle of the event loop that you are currently in.
11///
12/// Used to spawn tasks, sleep, dispatch events to the state and start IO operations.
13pub struct Context<
14    'a,
15    S: State,
16    const TASKS: usize,
17    const TASK_SIZE: usize,
18    const ROOT_TASK_SIZE: usize,
19    const TIMERS: usize,
20    const FDS: usize,
21> {
22    storage: LoopStorageGuard<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
23}
24
25impl<
26    'a,
27    S: State,
28    const TASKS: usize,
29    const TASK_SIZE: usize,
30    const ROOT_TASK_SIZE: usize,
31    const TIMERS: usize,
32    const FDS: usize,
33> Context<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
34{
35    pub(crate) fn new(
36        storage: LoopStorageGuard<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
37    ) -> Self {
38        Self { storage }
39    }
40
41    pub(crate) fn storage(
42        &self,
43    ) -> &LoopStorageGuard<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS> {
44        &self.storage
45    }
46
47    /// Dispatches given `event` on a state that was given to [`EventLoop`](crate::EventLoop).
48    pub fn dispatch(&self, event: S::Event) {
49        self.storage
50            .state_slot()
51            .borrow_mut()
52            .as_mut()
53            .expect("the state is set while tasks run")
54            .apply(event);
55    }
56
57    /// Spawns a task with a given async closure.
58    ///
59    /// # Panics
60    ///
61    /// Panics if:
62    ///
63    /// 1. all `TASKS` task slots are taken
64    /// 2. if the future is bigger than `TASK_SIZE` bytes
65    /// 3. if it is aligned to more than 16 bytes
66    ///
67    /// Use [`reserve_task`](Self::reserve_task) to wait for a free slot instead.
68    pub fn spawn<F, Fut>(&self, f: F) -> JoinHandle<'a, TASKS, TASK_SIZE, ROOT_TASK_SIZE>
69    where
70        F: FnOnce(Self) -> Fut,
71        Fut: Future<Output = ()> + 'a,
72    {
73        let id = self.storage.tasks().spawn(f(*self));
74        JoinHandle::new(self.storage.tasks(), id)
75    }
76
77    /// Reserves a task slot.
78    ///
79    /// This method returns a future that is resolved once a slot in the internal
80    /// pool of tasks is available.
81    ///
82    /// The future stays pending until some other task finishes and frees a slot.
83    pub fn reserve_task(
84        &self,
85    ) -> ReserveTask<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS> {
86        ReserveTask::new(self.storage)
87    }
88
89    pub(crate) fn spawn_root<F, Fut>(
90        storage: LoopStorageGuard<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
91        f: F,
92    ) where
93        F: FnOnce(Self) -> Fut,
94        Fut: Future<Output = ()> + 'a,
95    {
96        storage.tasks().spawn_root(f(Self::new(storage)));
97    }
98
99    /// Sleeps for `duration`.
100    pub fn sleep(&self, duration: Duration) -> Sleep<'_, TIMERS> {
101        Sleep::new(self.storage.timers(), Instant::now() + duration)
102    }
103
104    /// Runs `future` with a timeout of `duration`, resolves to `None` in case of a timeout.
105    pub fn timeout<F: Future>(&self, duration: Duration, future: F) -> Timeout<'_, F, TIMERS> {
106        Timeout::new(future, self.sleep(duration))
107    }
108}
109
110impl<
111    S: State,
112    const TASKS: usize,
113    const TASK_SIZE: usize,
114    const ROOT_TASK_SIZE: usize,
115    const TIMERS: usize,
116    const FDS: usize,
117> Clone for Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
118{
119    fn clone(&self) -> Self {
120        *self
121    }
122}
123
124impl<
125    S: State,
126    const TASKS: usize,
127    const TASK_SIZE: usize,
128    const ROOT_TASK_SIZE: usize,
129    const TIMERS: usize,
130    const FDS: usize,
131> Copy for Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
132{
133}
134
135impl<
136    S: State,
137    const TASKS: usize,
138    const TASK_SIZE: usize,
139    const ROOT_TASK_SIZE: usize,
140    const TIMERS: usize,
141    const FDS: usize,
142> core::fmt::Debug for Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
143{
144    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
145        f.write_str("Context")
146    }
147}