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
use std::io;
use std::task::{self, Poll};
use crate::SubmissionQueue;
use crate::kqueue::fd::OpKind;
use crate::kqueue::op::{Evented, State};
use crate::poll::PollableState;
pub(crate) struct PollableOp;
impl crate::op::Iter for PollableOp {
type Output = io::Result<()>;
type Resources = PollableState;
type Args = ();
type State = State<Evented, Self::Resources, Self::Args>;
fn poll_next(
state: &mut Self::State,
ctx: &mut task::Context<'_>,
sq: &SubmissionQueue,
) -> Poll<Option<Self::Output>> {
const OP: OpKind = OpKind::Read;
match &mut state.status {
Evented::NotStarted | Evented::ToSubmit => {
// SAFETY: status is not Complete so it's safe to access the resources.
let resources = unsafe { state.resources.assume_init_ref() };
// Add ourselves to the waiters for the operation.
let fd_state = &resources.state;
let needs_register = {
let mut fd_state = fd_state.lock();
let needs_register = !fd_state.has_waiting_op(OP);
fd_state.add(OP, ctx.waker().clone());
needs_register
}; // Unlock fd state.
// If we're to first we need to register an event with the
// kernel.
if needs_register {
sq.submissions().add(|event| {
event.0.filter = libc::EVFILT_READ;
event.0.ident = resources.sq.submissions().fd().cast_unsigned() as _;
event.0.udata = fd_state.as_udata();
});
}
// Set ourselves to waiting for an event from the kernel.
state.status = Evented::Waiting;
// We've added our waker above to the list, we'll be woken up
// once we can make progress.
Poll::Pending
}
Evented::Waiting => {
// SAFETY: status is not Complete so it's safe to access the resources.
let resources = unsafe { state.resources.assume_init_ref() };
if resources.state.lock().has_waiting_op(OP) {
// Polled before we got an event.
Poll::Pending
} else {
// Return Ok and reset the state to wait for another event.
state.status = Evented::ToSubmit;
Poll::Ready(Some(Ok(())))
}
}
Evented::Complete => Poll::Ready(None),
}
}
}