Skip to content

Commit

Permalink
Implement AsFd and bidirectional conversion to/from OwnedFd
Browse files Browse the repository at this point in the history
In particular, this makes it possible to get a `BorrowedFd` from an
`Inotify`, which allows integration with polling mechanisms that don't
use `RawFd`. This will be needed to work with the next version of
`async-io`.
  • Loading branch information
joshtriplett committed Jun 6, 2023
1 parent 9ec50c5 commit 1e98f61
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/fd_guard.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use std::{
ops::Deref,
os::fd::{
AsFd,
BorrowedFd,
},
os::unix::io::{
AsRawFd,
FromRawFd,
Expand Down Expand Up @@ -77,6 +81,13 @@ impl AsRawFd for FdGuard {
}
}

impl AsFd for FdGuard {
#[inline]
fn as_fd(&self) -> BorrowedFd<'_> {
unsafe { BorrowedFd::borrow_raw(self.fd) }
}
}

impl PartialEq for FdGuard {
fn eq(&self, other: &FdGuard) -> bool {
self.fd == other.fd
Expand Down
24 changes: 24 additions & 0 deletions src/inotify.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use std::{
io,
os::fd::{
AsFd,
BorrowedFd,
OwnedFd,
},
os::unix::io::{
AsRawFd,
FromRawFd,
Expand Down Expand Up @@ -370,3 +375,22 @@ impl IntoRawFd for Inotify {
self.fd.fd
}
}

impl AsFd for Inotify {
#[inline]
fn as_fd(&self) -> BorrowedFd<'_> {
self.fd.as_fd()
}
}

impl From<Inotify> for OwnedFd {
fn from(fd: Inotify) -> OwnedFd {
unsafe { OwnedFd::from_raw_fd(fd.into_raw_fd()) }
}
}

impl From<OwnedFd> for Inotify {
fn from(fd: OwnedFd) -> Inotify {
unsafe { Inotify::from_raw_fd(fd.into_raw_fd()) }
}
}

0 comments on commit 1e98f61

Please sign in to comment.