Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a slice for the event list of kevent() #1044

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions examples/kq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ fn main() -> std::io::Result<()> {
use rustix::{fd::AsRawFd, fs};

let kq = kqueue()?;
let mut out = Vec::with_capacity(10);
let mut buf: Events<10> = Events::new();

#[cfg(feature = "fs")]
let dir = fs::openat(
Expand Down Expand Up @@ -59,10 +59,11 @@ fn main() -> std::io::Result<()> {
eprintln!("Run with --features process to enable more!");
#[cfg(not(feature = "fs"))]
eprintln!("Run with --features fs to enable more!");
unsafe { kevent(&kq, &subs, &mut out, None) }?;

loop {
while let Some(e) = out.pop() {
let events = unsafe { kevent(&kq, &subs, &mut buf, None) }?;

for e in events {
match e.filter() {
#[cfg(feature = "process")]
EventFilter::Signal { signal, times } => {
Expand All @@ -79,7 +80,6 @@ fn main() -> std::io::Result<()> {
_ => eprintln!("Unknown event"),
}
}
unsafe { kevent(&kq, &[], &mut out, None) }?;
}
}

Expand Down
63 changes: 45 additions & 18 deletions src/event/kqueue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use backend::c::{self, intptr_t, kevent as kevent_t, uintptr_t};
use backend::event::syscalls;

use alloc::vec::Vec;
use core::mem::zeroed;
use core::mem::{zeroed, MaybeUninit};
use core::ptr::slice_from_raw_parts_mut;
use core::time::Duration;

Expand Down Expand Up @@ -155,6 +155,39 @@ impl Event {
}
}

impl Default for Event {
fn default() -> Self {
Event {
inner: kevent_t {
..unsafe { zeroed() }
},
}
}
}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As Event implements Clone I think this is technically not required, as we can just do the zero'ing in the Events type. This is in fact probably better such that users can't create a zero'd (and thus basically invalid) Event type themselves.


/// A buffer for storing [`Event`] values _produced_ by the [`kevent`] function.
pub struct Events<const N: usize> {
inner: [Event; N],
}

impl<const N: usize> Events<N> {
/// Returns a new buffer with enough space for `N` events.
///
/// # Examples
///
/// ```no_run
/// use rustix::event::kqueue::Events;
///
/// // Create a buffer that can hold up to 10 events.
/// let events: Events<10> = Events::new();
/// ```
pub fn new() -> Events<N> {
Events {
inner: [Event::default(); N],
}
}
}

/// Bottom 24 bits of a u32.
#[cfg(any(apple, freebsdlike))]
const EVFILT_USER_FLAGS: u32 = 0x00ff_ffff;
Expand Down Expand Up @@ -398,8 +431,9 @@ pub fn kqueue() -> io::Result<OwnedFd> {
/// `kevent(kqueue, changelist, eventlist, timeout)`—Wait for events on a
/// `kqueue`.
///
/// Note: in order to receive events, make sure to allocate capacity in the
/// eventlist! Otherwise, the function will return immediately.
/// In order to receive one or more events, the slice passed to the `eventlist`
/// argument must have a length of at least one. If the slice is empty, this
/// function returns immediately _even if_ a timeout is specified.
///
/// # Safety
///
Expand All @@ -418,32 +452,25 @@ pub fn kqueue() -> io::Result<OwnedFd> {
/// [OpenBSD]: https://man.openbsd.org/kevent.2
/// [NetBSD]: https://man.netbsd.org/kevent.2
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=kevent&section=2
pub unsafe fn kevent(
pub unsafe fn kevent<'a, const N: usize>(
kqueue: impl AsFd,
changelist: &[Event],
eventlist: &mut Vec<Event>,
eventlist: &'a mut Events<N>,
timeout: Option<Duration>,
) -> io::Result<usize> {
) -> io::Result<&'a [Event]> {
let timeout = timeout.map(|timeout| backend::c::timespec {
tv_sec: timeout.as_secs() as _,
tv_nsec: timeout.subsec_nanos() as _,
});

// Populate the event list with events.
eventlist.set_len(0);
let out_slice = slice_from_raw_parts_mut(eventlist.as_mut_ptr().cast(), eventlist.capacity());
let res = syscalls::kevent(
let out_slice =
slice_from_raw_parts_mut(eventlist.inner.as_mut_ptr().cast(), eventlist.inner.len());

syscalls::kevent(
kqueue.as_fd(),
changelist,
&mut *out_slice,
timeout.as_ref(),
)
.map(|res| res as _);

// Update the event list.
if let Ok(len) = res {
eventlist.set_len(len);
}

res
.map(|res| &eventlist.inner[0..(res as usize)])
}