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