Skip to content

Commit

Permalink
Use a slice for the event list of kevent()
Browse files Browse the repository at this point in the history
This removes the need for dynamically allocating a Vec when the kevent()
function is called. The documentation is also rephrased slightly as
slices don't really have a "capacity", but only a fixed-size length.

This fixes #1043.
  • Loading branch information
yorickpeterse committed Apr 5, 2024
1 parent fa21a6d commit f0c55cc
Showing 1 changed file with 8 additions and 15 deletions.
23 changes: 8 additions & 15 deletions src/event/kqueue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,8 +398,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 @@ -421,29 +422,21 @@ pub fn kqueue() -> io::Result<OwnedFd> {
pub unsafe fn kevent(
kqueue: impl AsFd,
changelist: &[Event],
eventlist: &mut Vec<Event>,
eventlist: &mut [Event],
timeout: Option<Duration>,
) -> io::Result<usize> {
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.as_mut_ptr().cast(), eventlist.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| res as _)
}

0 comments on commit f0c55cc

Please sign in to comment.