Skip to main content

externally_driven_async_rt/
context.rs

1use core::{cell::RefCell, future::Future, time::Duration};
2
3use crate::{
4    claimed::Claimed,
5    io::IoIndex,
6    notify::Notified,
7    selector::{EVENTS_PER_CALL, Selector, SelectorEvent},
8    state::State,
9    storage::LoopStorage,
10    tasks::{JoinHandle, ReserveTask},
11    time::{Instant, Sleep, Timeout},
12};
13
14/// A handle of the event loop that you are currently in.
15///
16/// Used to spawn tasks, sleep, dispatch events to the state and start IO operations.
17#[must_use]
18pub struct Context<
19    'a,
20    S: State,
21    const TASKS: usize,
22    const TASK_SIZE: usize,
23    const ROOT_TASK_SIZE: usize,
24    const TIMERS: usize,
25    const FDS: usize,
26> {
27    pub(crate) storage: &'static LoopStorage<TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
28    pub(crate) selector: &'a Selector,
29    pub(crate) state: &'a RefCell<S>,
30    pub(crate) claimed: Claimed<'a>,
31}
32
33impl<
34    'a,
35    S: State,
36    const TASKS: usize,
37    const TASK_SIZE: usize,
38    const ROOT_TASK_SIZE: usize,
39    const TIMERS: usize,
40    const FDS: usize,
41> Context<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
42{
43    pub(crate) fn claim(
44        storage: &'static LoopStorage<TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
45        selector: &'a Selector,
46        state: &'a RefCell<S>,
47    ) -> Self {
48        storage.tasks.queue.claim();
49        Self {
50            storage,
51            selector,
52            state,
53            // SAFETY: claiming the queue above panics unless this is the storage's first claim, so
54            // these tasks belong to this loop alone. Only the `EventLoop<'a>` that owns this claim
55            // polls and drops them, and it drops them all before `'a` ends or, if leaked, never
56            // touches them again.
57            claimed: unsafe { Claimed::new() },
58        }
59    }
60
61    /// Dispatches given `event` on a state that was given to [`EventLoop`](crate::EventLoop).
62    pub fn dispatch(&self, event: S::Event) {
63        self.state.borrow_mut().apply(event);
64    }
65
66    /// Spawns a task with a given async closure.
67    ///
68    /// # Panics
69    ///
70    /// Panics if:
71    ///
72    /// 1. all `TASKS` task slots are taken
73    /// 2. if the future is bigger than `TASK_SIZE` bytes
74    /// 3. if it is aligned to more than 16 bytes
75    ///
76    /// Use [`reserve_task`](Self::reserve_task) to wait for a free slot instead.
77    pub fn spawn<F, Fut>(&self, f: F) -> JoinHandle<TASKS, TASK_SIZE, ROOT_TASK_SIZE>
78    where
79        F: FnOnce(Self) -> Fut,
80        Fut: Future<Output = ()> + 'a,
81    {
82        let future = f(*self);
83        let id = self.storage.tasks.spawn(self.claimed, future);
84        JoinHandle::new(&self.storage.tasks, id)
85    }
86
87    /// Reserves a task slot.
88    ///
89    /// This method returns a future that is resolved once a slot in the internal
90    /// pool of tasks is available.
91    ///
92    /// The future stays pending until some other task finishes and frees a slot.
93    ///
94    /// # Cancel safety
95    ///
96    /// This method is cancel safe.
97    pub const fn reserve_task(&self) -> ReserveTask<'a, TASKS, TASK_SIZE, ROOT_TASK_SIZE> {
98        ReserveTask::new(&self.storage.tasks, self.claimed)
99    }
100
101    /// Sleeps for `duration`.
102    ///
103    /// # Cancel safety
104    ///
105    /// This method is cancel safe.
106    pub fn sleep(&self, duration: Duration) -> Sleep<'_, TIMERS> {
107        Sleep::new(
108            &self.storage.timers,
109            Instant::now().saturating_add(duration),
110        )
111    }
112
113    /// Runs `future` with a timeout of `duration`, resolves to `None` in case of a timeout.
114    ///
115    /// # Cancel safety
116    ///
117    /// This method is cancel safe if `future` is.
118    pub fn timeout<F: Future>(&self, duration: Duration, future: F) -> Timeout<'_, F, TIMERS> {
119        Timeout::new(future, self.sleep(duration))
120    }
121
122    /// Waits until [`EventLoop::notify`](crate::EventLoop::notify) is called.
123    ///
124    /// See [`Notified`] for details.
125    ///
126    /// # Cancel safety
127    ///
128    /// This method is cancel safe.
129    pub const fn notified(&self) -> Notified<'_> {
130        Notified::new(&self.storage.notification)
131    }
132
133    pub(crate) fn clear(&self) {
134        self.storage.tasks.drop_all();
135        self.storage.timers.clear();
136        self.storage.io_waiters.clear();
137        self.storage.notification.clear();
138    }
139
140    pub(crate) fn process_selector_events(&self) -> rustix::io::Result<()> {
141        let mut events = [None; EVENTS_PER_CALL];
142        loop {
143            let full = self.selector.poll_nonblocking(&mut events)?;
144            for event in events.iter().map_while(|event| *event) {
145                match event {
146                    SelectorEvent::Io { token, ready } => {
147                        self.storage
148                            .io_waiters
149                            .wake_ready(IoIndex::from_bits(token), ready);
150                    }
151                    SelectorEvent::Notify => self.storage.notification.fire(),
152                    SelectorEvent::Timer => {
153                        let now = Instant::now();
154                        while let Some(waker) = self.storage.timers.take_expired(now) {
155                            waker.wake();
156                        }
157                    }
158                }
159            }
160            if !full {
161                return Ok(());
162            }
163        }
164    }
165
166    pub(crate) fn flush(&self) -> rustix::io::Result<()> {
167        match self.storage.timers.next_deadline() {
168            Some(deadline) => self.selector.arm_timer(deadline),
169            None => self.selector.disarm_timer(),
170        }
171        self.selector
172            .flush(self.storage.io_waiters.pending_changes())?;
173        self.storage.io_waiters.mark_flushed();
174        Ok(())
175    }
176}
177
178impl<
179    S: State,
180    const TASKS: usize,
181    const TASK_SIZE: usize,
182    const ROOT_TASK_SIZE: usize,
183    const TIMERS: usize,
184    const FDS: usize,
185> Clone for Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
186{
187    fn clone(&self) -> Self {
188        *self
189    }
190}
191
192impl<
193    S: State,
194    const TASKS: usize,
195    const TASK_SIZE: usize,
196    const ROOT_TASK_SIZE: usize,
197    const TIMERS: usize,
198    const FDS: usize,
199> Copy for Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
200{
201}
202
203impl<
204    S: State,
205    const TASKS: usize,
206    const TASK_SIZE: usize,
207    const ROOT_TASK_SIZE: usize,
208    const TIMERS: usize,
209    const FDS: usize,
210> core::fmt::Debug for Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
211{
212    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
213        f.write_str("Context")
214    }
215}