forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect.rs
More file actions
319 lines (277 loc) · 8.04 KB
/
Copy pathselect.rs
File metadata and controls
319 lines (277 loc) · 8.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
use core::mem::MaybeUninit;
use std::io;
#[cfg(unix)]
pub mod platform {
pub use libc::pollfd;
pub use libc::{FD_ISSET, FD_SET, FD_SETSIZE, FD_ZERO, fd_set, select, timeval};
use std::io;
pub use std::os::unix::io::RawFd;
#[must_use]
pub const fn check_err(x: i32) -> bool {
x < 0
}
pub fn last_select_error() -> io::Error {
io::Error::last_os_error()
}
}
#[allow(non_snake_case)]
#[cfg(windows)]
pub mod platform {
pub use WinSock::{FD_SET as fd_set, FD_SETSIZE, SOCKET as RawFd, TIMEVAL as timeval, select};
use std::io;
use windows_sys::Win32::Networking::WinSock;
/// # Safety
///
/// `set` must be a valid mutable pointer to an initialized WinSock fd_set.
pub unsafe fn FD_SET(fd: RawFd, set: *mut fd_set) {
let mut slot = unsafe { (&raw mut (*set).fd_array).cast::<RawFd>() };
let fd_count = unsafe { (*set).fd_count };
for _ in 0..fd_count {
if unsafe { *slot } == fd {
return;
}
slot = unsafe { slot.add(1) };
}
if fd_count < FD_SETSIZE {
unsafe {
*slot = fd as RawFd;
(*set).fd_count += 1;
}
}
}
/// # Safety
///
/// `set` must be a valid mutable pointer to a WinSock fd_set.
pub unsafe fn FD_ZERO(set: *mut fd_set) {
unsafe { (*set).fd_count = 0 };
}
/// # Safety
///
/// `set` must be a valid mutable pointer to an initialized WinSock fd_set.
pub unsafe fn FD_ISSET(fd: RawFd, set: *mut fd_set) -> bool {
use WinSock::__WSAFDIsSet;
unsafe { __WSAFDIsSet(fd as _, set) != 0 }
}
#[must_use]
pub fn check_err(x: i32) -> bool {
x == WinSock::SOCKET_ERROR
}
pub fn last_select_error() -> io::Error {
io::Error::from_raw_os_error(unsafe { WinSock::WSAGetLastError() })
}
}
#[cfg(target_os = "wasi")]
pub mod platform {
pub use libc::{FD_SETSIZE, timeval};
use std::io;
pub use std::os::fd::RawFd;
pub const fn check_err(x: i32) -> bool {
x < 0
}
#[repr(C)]
pub struct fd_set {
__nfds: usize,
__fds: [libc::c_int; FD_SETSIZE],
}
#[allow(non_snake_case)]
/// # Safety
///
/// `set` must be a valid pointer to an initialized fd_set.
pub unsafe fn FD_ISSET(fd: RawFd, set: *const fd_set) -> bool {
let set = unsafe { &*set };
for p in &set.__fds[..set.__nfds] {
if *p == fd {
return true;
}
}
false
}
#[allow(non_snake_case)]
/// # Safety
///
/// `set` must be a valid mutable pointer to an initialized fd_set.
pub unsafe fn FD_SET(fd: RawFd, set: *mut fd_set) {
let set = unsafe { &mut *set };
for p in &set.__fds[..set.__nfds] {
if *p == fd {
return;
}
}
let n = set.__nfds;
if n < FD_SETSIZE {
set.__fds[n] = fd;
set.__nfds = n + 1;
}
}
#[allow(non_snake_case)]
/// # Safety
///
/// `set` must be a valid mutable pointer to an fd_set.
pub unsafe fn FD_ZERO(set: *mut fd_set) {
unsafe { (*set).__nfds = 0 };
}
unsafe extern "C" {
pub fn select(
nfds: libc::c_int,
readfds: *mut fd_set,
writefds: *mut fd_set,
errorfds: *mut fd_set,
timeout: *const timeval,
) -> libc::c_int;
}
pub fn last_select_error() -> io::Error {
io::Error::last_os_error()
}
}
pub use platform::{RawFd, timeval};
#[cfg(unix)]
pub type PollFd = platform::pollfd;
#[repr(transparent)]
pub struct FdSet(MaybeUninit<platform::fd_set>);
impl FdSet {
pub fn new() -> Self {
let mut fdset = MaybeUninit::zeroed();
unsafe { platform::FD_ZERO(fdset.as_mut_ptr()) };
Self(fdset)
}
pub fn insert(&mut self, fd: RawFd) {
unsafe { platform::FD_SET(fd, self.0.as_mut_ptr()) };
}
pub fn contains(&mut self, fd: RawFd) -> bool {
unsafe { platform::FD_ISSET(fd, self.0.as_mut_ptr()) }
}
pub fn clear(&mut self) {
unsafe { platform::FD_ZERO(self.0.as_mut_ptr()) };
}
pub fn highest(&mut self) -> Option<RawFd> {
(0..platform::FD_SETSIZE as RawFd)
.rev()
.find(|&fd| self.contains(fd))
}
}
impl Default for FdSet {
fn default() -> Self {
Self::new()
}
}
pub fn select(
nfds: libc::c_int,
readfds: &mut FdSet,
writefds: &mut FdSet,
errfds: &mut FdSet,
timeout: Option<&mut timeval>,
) -> io::Result<i32> {
let timeout = match timeout {
Some(tv) => tv as *mut timeval,
None => core::ptr::null_mut(),
};
let ret = unsafe {
platform::select(
nfds,
readfds.0.as_mut_ptr(),
writefds.0.as_mut_ptr(),
errfds.0.as_mut_ptr(),
timeout,
)
};
if platform::check_err(ret) {
Err(platform::last_select_error())
} else {
Ok(ret)
}
}
pub fn sec_to_timeval(sec: f64) -> timeval {
timeval {
tv_sec: sec.trunc() as _,
tv_usec: (sec.fract() * 1e6) as _,
}
}
#[cfg(unix)]
#[inline]
pub fn search_poll_fd(fds: &[PollFd], fd: i32) -> Result<usize, usize> {
fds.binary_search_by_key(&fd, |pfd| pfd.fd)
}
#[cfg(unix)]
pub fn insert_poll_fd(fds: &mut Vec<PollFd>, fd: i32, events: i16) {
match search_poll_fd(fds, fd) {
Ok(i) => fds[i].events = events,
Err(i) => fds.insert(
i,
PollFd {
fd,
events,
revents: 0,
},
),
}
}
#[cfg(unix)]
pub fn get_poll_fd_mut(fds: &mut [PollFd], fd: i32) -> Option<&mut PollFd> {
search_poll_fd(fds, fd).ok().map(move |i| &mut fds[i])
}
#[cfg(unix)]
pub fn remove_poll_fd(fds: &mut Vec<PollFd>, fd: i32) -> Option<PollFd> {
search_poll_fd(fds, fd).ok().map(|i| fds.remove(i))
}
#[cfg(unix)]
pub fn poll_fds(fds: &mut [PollFd], timeout: i32) -> std::io::Result<i32> {
let res = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as _, timeout) };
if res < 0 {
Err(std::io::Error::last_os_error())
} else {
Ok(res)
}
}
#[cfg(any(target_os = "linux", target_os = "android", target_os = "redox"))]
pub mod epoll {
use std::os::fd::{AsFd, IntoRawFd, OwnedFd};
pub use rustix::event::Timespec;
pub use rustix::event::epoll::{Event, EventData, EventFlags};
#[derive(Debug)]
pub enum WaitError {
Interrupted,
Io(std::io::Error),
}
pub fn create() -> std::io::Result<OwnedFd> {
rustix::event::epoll::create(rustix::event::epoll::CreateFlags::CLOEXEC).map_err(Into::into)
}
pub fn close(fd: OwnedFd) -> nix::Result<()> {
nix::unistd::close(fd.into_raw_fd())
}
pub fn add<F: AsFd>(epoll: &OwnedFd, fd: F, data: u64, events: u32) -> std::io::Result<()> {
rustix::event::epoll::add(
epoll,
fd,
EventData::new_u64(data),
EventFlags::from_bits_retain(events),
)
.map_err(Into::into)
}
pub fn modify<F: AsFd>(epoll: &OwnedFd, fd: F, data: u64, events: u32) -> std::io::Result<()> {
rustix::event::epoll::modify(
epoll,
fd,
EventData::new_u64(data),
EventFlags::from_bits_retain(events),
)
.map_err(Into::into)
}
pub fn delete<F: AsFd>(epoll: &OwnedFd, fd: F) -> std::io::Result<()> {
rustix::event::epoll::delete(epoll, fd).map_err(Into::into)
}
pub fn wait(
epoll: &OwnedFd,
events: &mut Vec<Event>,
timeout: Option<&Timespec>,
) -> Result<usize, WaitError> {
events.clear();
match rustix::event::epoll::wait(epoll, rustix::buffer::spare_capacity(events), timeout) {
Ok(n) => {
unsafe { events.set_len(n) };
Ok(n)
}
Err(rustix::io::Errno::INTR) => Err(WaitError::Interrupted),
Err(err) => Err(WaitError::Io(err.into())),
}
}
}