Skip to main content

externally_driven_async_rt/event_loop/
mod.rs

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