Skip to main content

externally_driven_async_rt/event_loop/
error.rs

1/// An error that can be returned from an [`EventLoop`](crate::EventLoop).
2#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3pub enum EventLoopError {
4    /// An epoll or kqueue call failed.
5    Io(rustix::io::Errno),
6    /// [`EventLoop::drain_events_without_blocking`](crate::EventLoop::drain_events_without_blocking)
7    /// is called on the [`EventLoop`](crate::EventLoop) that has already finished
8    RootFinished,
9    /// [`EventLoop::new`](crate::EventLoop::new) is called with a
10    /// [`LoopStorage`](crate::LoopStorage) that has already been used by another
11    /// [`EventLoop`](crate::EventLoop). A storage backs at most one event loop for the whole
12    /// program, even after that loop has finished.
13    StorageAlreadyUsed,
14}
15
16impl core::fmt::Display for EventLoopError {
17    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
18        match self {
19            Self::Io(errno) => write!(f, "event loop IO error: {errno}"),
20            Self::RootFinished => f.write_str("the root future has finished"),
21            Self::StorageAlreadyUsed => {
22                f.write_str("the storage has already been used by another event loop")
23            }
24        }
25    }
26}
27
28impl core::error::Error for EventLoopError {}
29
30impl From<rustix::io::Errno> for EventLoopError {
31    fn from(errno: rustix::io::Errno) -> Self {
32        Self::Io(errno)
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::EventLoopError;
39
40    #[test]
41    fn errors_display_their_cause() {
42        struct StartsWith<'a>(&'a str);
43
44        impl core::fmt::Write for StartsWith<'_> {
45            fn write_str(&mut self, s: &str) -> core::fmt::Result {
46                match self.0.strip_prefix(s) {
47                    Some(rest) => self.0 = rest,
48                    None if self.0.is_empty() => {}
49                    None => return Err(core::fmt::Error),
50                }
51                Ok(())
52            }
53        }
54
55        for (error, expected) in [
56            (EventLoopError::RootFinished, "the root future has finished"),
57            (
58                EventLoopError::Io(rustix::io::Errno::BADF),
59                "event loop IO error: ",
60            ),
61            (
62                EventLoopError::StorageAlreadyUsed,
63                "the storage has already been used by another event loop",
64            ),
65        ] {
66            let mut prefix = StartsWith(expected);
67            core::fmt::write(&mut prefix, format_args!("{error}")).unwrap();
68            assert_eq!(prefix.0, "", "{error:?}");
69        }
70    }
71}