poller/
lib.rs

1/// 定时事件枚举。
2#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3pub enum Event {
4    /// 没有事件。
5    None,
6    /// 数据到达。
7    Read,
8    /// 目标可写。
9    Write,
10    /// 发生错误。
11    Error,
12    /// 边沿触发。
13    EdgeTriggered,
14    /// 已经挂起。
15    HangUp,
16    /// 单次触发。
17    OneShot,
18}
19
20/// 定义事件集合。
21///
22/// # Examples
23///
24/// ```
25/// use poller::Events;
26/// let events = Events::new().with_read();
27/// ```
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub struct Events(u32);
30
31impl std::fmt::Display for Events {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        write!(f, "0x{:08X}", self.0)
34    }
35}
36
37impl Events {
38    /// 创建一个新的事件集合。
39    pub fn new() -> Self {
40        Self { 0: 0 }
41    }
42
43    /// 清空当前值且返回一个空事件集合。
44    pub fn none(mut self) -> Self {
45        self.0 = 0;
46        self
47    }
48
49    /// 附加数据到达事件到集合中。
50    pub fn read(mut self) -> Self {
51        self.0 |= 1 << Event::Read as u32;
52        self
53    }
54
55    /// 附加目标可写事件到集合中。
56    pub fn write(mut self) -> Self {
57        self.0 |= 1 << Event::Write as u32;
58        self
59    }
60
61    /// 附加发生错误事件到集合中。
62    pub fn error(mut self) -> Self {
63        self.0 |= 1 << Event::Error as u32;
64        self
65    }
66
67    /// 检查集合是否为空。
68    pub fn is_none(self) -> bool {
69        self.0 == 0
70    }
71
72    /// 检查集合是否有数据到达事件。
73    pub fn has_read(self) -> bool {
74        (self.0 & (1 << Event::Read as u32)) != 0
75    }
76
77    /// 检查集合是否有目标可写事件。
78    pub fn has_write(self) -> bool {
79        (self.0 & (1 << Event::Write as u32)) != 0
80    }
81
82    /// 检查集合是否有发生错误事件。
83    pub fn has_error(self) -> bool {
84        (self.0 & (1 << Event::Error as u32)) != 0
85    }
86}
87
88/// 定义系统错误。
89#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
90pub struct SysError(i32);
91
92impl std::fmt::Display for SysError {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        write!(f, r#"Code={}, Reason="{{}}")"#, self.0)
95    }
96}
97
98impl std::error::Error for SysError {}
99
100impl From<i32> for SysError {
101    fn from(val: i32) -> Self {
102        Self { 0: val }
103    }
104}
105
106impl Into<i32> for SysError {
107    fn into(self) -> i32 {
108        self.0
109    }
110}
111
112impl SysError {
113    /// 从系统当前 errno 创建一个 SysError 对象。
114    pub fn last() -> Self {
115        unsafe {
116            Self {
117                0: *(libc::__errno_location()),
118            }
119        }
120    }
121}
122
123#[cfg(target_os = "linux")]
124pub mod epoll;
125
126#[cfg(target_os = "linux")]
127#[doc(inline)]
128pub use epoll::{EventContext, EventData, Poller};
129
130#[cfg(not(target_os = "linux"))]
131pub mod select;
132
133#[cfg(test)]
134mod tests {}