Skip to main content

externally_driven_async_rt/event_loop/
mod.rs

1mod error;
2
3use core::cell::RefMut;
4
5use rustix::fd::{AsFd, AsRawFd, BorrowedFd, RawFd};
6
7pub use self::error::Error;
8
9use crate::{
10    context::Context,
11    selector::Selector,
12    state::State,
13    storage::{LoopStorage, LoopStorageGuard},
14    tasks::{Root, RootStatus},
15};
16
17/// The main type, an event loop.
18pub struct EventLoop<
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    storage: LoopStorageGuard<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
28}
29
30impl<
31    'a,
32    S: State,
33    const TASKS: usize,
34    const TASK_SIZE: usize,
35    const ROOT_TASK_SIZE: usize,
36    const TIMERS: usize,
37    const FDS: usize,
38> EventLoop<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
39{
40    /// Creates an event loop and polls given future once.
41    ///
42    /// # Panics
43    ///
44    /// Panics if:
45    ///
46    /// 1. `storage` has already been used by another event loop
47    /// 2. the future is bigger than `ROOT_TASK_SIZE` bytes
48    /// 3. the future is aligned to more than 16 bytes.
49    pub fn new<F, Fut>(
50        storage: &'static LoopStorage<S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
51        selector: &'a mut Selector,
52        state: S,
53        f: F,
54    ) -> Result<Self, Error>
55    where
56        F: FnOnce(Context<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>) -> Fut,
57        Fut: Future<Output = ()> + 'a,
58    {
59        let storage = storage.claim(selector, state);
60        let event_loop = Self { storage };
61        Context::spawn_root(storage, f);
62        match storage.tasks().run_ready() {
63            RootStatus::Running => {}
64            RootStatus::Finished => return Err(Error::RootFinished),
65        }
66        event_loop.finish_drain(RootStatus::Running)?;
67        Ok(event_loop)
68    }
69
70    /// Drains all events from the underlying `epollfd` or `kqueuefd`,
71    /// polls woken futures until none is ready,
72    /// submits them back to epoll/kqueue.
73    pub fn drain_events_without_blocking(&mut self) -> Result<(), Error> {
74        let storage = self.storage;
75        if let Root::Finished = storage.tasks().root() {
76            return Err(Error::RootFinished);
77        }
78        let status = loop {
79            storage.process_selector_events().map_err(Error::Io)?;
80            if !storage.tasks().has_ready() {
81                break RootStatus::Running;
82            }
83            if storage.tasks().run_ready() == RootStatus::Finished {
84                break RootStatus::Finished;
85            }
86        };
87        self.finish_drain(status)
88    }
89
90    /// Returns a mutable reference to the stored state.
91    ///
92    /// This is the only way to communicate with the external world.
93    pub fn state_mut(&mut self) -> RefMut<'_, S> {
94        RefMut::map(self.storage.state_slot().borrow_mut(), |state| {
95            state
96                .as_mut()
97                .expect("the state is set until the loop is dropped")
98        })
99    }
100
101    fn finish_drain(&self, status: RootStatus) -> Result<(), Error> {
102        if status == RootStatus::Finished {
103            self.storage.tasks().drop_all();
104        }
105        self.storage.flush().map_err(Error::Io)?;
106        match status {
107            RootStatus::Running => Ok(()),
108            RootStatus::Finished => Err(Error::RootFinished),
109        }
110    }
111
112    #[cfg(test)]
113    pub(crate) fn storage(
114        &self,
115    ) -> LoopStorageGuard<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS> {
116        self.storage
117    }
118}
119
120impl<
121    'a,
122    S: State,
123    const TASKS: usize,
124    const TASK_SIZE: usize,
125    const ROOT_TASK_SIZE: usize,
126    const TIMERS: usize,
127    const FDS: usize,
128> Drop for EventLoop<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
129{
130    fn drop(&mut self) {
131        self.storage.clear();
132        drop(self.storage.state_slot().borrow_mut().take());
133    }
134}
135
136impl<
137    'a,
138    S: State,
139    const TASKS: usize,
140    const TASK_SIZE: usize,
141    const ROOT_TASK_SIZE: usize,
142    const TIMERS: usize,
143    const FDS: usize,
144> AsFd for EventLoop<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
145{
146    fn as_fd(&self) -> BorrowedFd<'_> {
147        self.storage.selector().as_fd()
148    }
149}
150
151impl<
152    'a,
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> AsRawFd for EventLoop<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
160{
161    fn as_raw_fd(&self) -> RawFd {
162        self.as_fd().as_raw_fd()
163    }
164}
165
166impl<
167    'a,
168    S: State,
169    const TASKS: usize,
170    const TASK_SIZE: usize,
171    const ROOT_TASK_SIZE: usize,
172    const TIMERS: usize,
173    const FDS: usize,
174> core::fmt::Debug for EventLoop<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
175{
176    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
177        f.write_str("EventLoop")
178    }
179}
180
181#[cfg(test)]
182mod tests;