1use std::{
2 marker,
3 os::fd::{AsRawFd as _, BorrowedFd},
4 slice,
5};
6
7use o3::base::marker::ThreadBound;
8
9use crate::{
10 Errno,
11 io::poll,
12 kernel::{self, errno},
13};
14
15pub mod raw;
16
17pub const MAX_ENTRIES: usize = libc::nfds_t::MAX as usize;
19
20#[derive(Clone, Copy, Debug)]
22#[repr(transparent)]
23pub struct Entry<'fd>(
24 libc::pollfd,
25 marker::PhantomData<(BorrowedFd<'fd>, ThreadBound)>,
26);
27
28impl<'fd> Entry<'fd> {
29 pub fn readable(fd: BorrowedFd<'fd>) -> Self {
31 Self::new(fd, libc::POLLIN)
32 }
33
34 pub fn writable(fd: BorrowedFd<'fd>) -> Self {
36 Self::new(fd, libc::POLLOUT)
37 }
38
39 fn new(fd: BorrowedFd<'fd>, events: libc::c_short) -> Self {
40 Self(
41 libc::pollfd {
42 fd: fd.as_raw_fd(),
43 events,
44 revents: 0,
45 },
46 marker::PhantomData,
47 )
48 }
49
50 pub const fn is_ready(self) -> bool {
52 self.0.revents != 0
53 }
54
55 pub const fn is_readable(self) -> bool {
57 self.0.revents & libc::POLLIN != 0
58 }
59
60 pub const fn revents(self) -> i16 {
62 self.0.revents
63 }
64
65 pub fn retire(&mut self) {
67 self.0.fd = -1;
68 self.0.revents = 0;
69 }
70}
71
72fn raw<'a>(entries: &'a mut [Entry<'_>]) -> &'a mut [libc::pollfd] {
74 unsafe { slice::from_raw_parts_mut(entries.as_mut_ptr().cast(), entries.len()) }
77}
78
79pub struct Events<'a, 'fd> {
80 entries: &'a [Entry<'fd>],
81 count: usize,
82}
83
84impl<'a, 'fd> Events<'a, 'fd> {
85 pub const fn count(&self) -> usize {
86 self.count
87 }
88 pub const fn entries(&self) -> &'a [Entry<'fd>] {
89 self.entries
90 }
91}
92
93pub trait Poll: errno::Source {
95 fn wait<'a, 'fd: 'a, T: poll::raw::Entries<'fd>, E: From<Errno>>(
96 owner: &'a mut T,
97 timeout: i32,
98 ) -> Result<poll::Events<'a, 'fd>, E> {
99 const {
100 assert!(T::MAX <= MAX_ENTRIES);
101 }
102 let entries = owner.entries();
103 let raw = raw(entries);
104 let raw = unsafe { libc::poll(raw.as_mut_ptr(), raw.len() as libc::nfds_t, timeout) };
106 let count = unsafe { kernel::raw::Status::new(raw).try_count::<Self, E>() }?.get();
108 Ok(poll::Events { entries, count })
109 }
110}
111
112impl<T: errno::Source> Poll for T {}