Skip to content

Commit bb00248

Browse files
authored
Implement dirfd equivalent functions (#1549)
Implement functions that allow us to retrieve the directory stream file descriptor, equivalent to libc's `dirfd` function. On linux, we can simply return the file descriptor itself (I verified this is what musl does).
1 parent cea123c commit bb00248

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/backend/libc/fs/dir.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,27 @@ impl Dir {
7575
}
7676
}
7777

78+
/// Returns the file descriptor associated with the directory stream.
79+
///
80+
/// The file descriptor is used internally by the directory stream. As a result, it is useful
81+
/// only for functions which do not depend or alter the file position.
82+
///
83+
/// # References
84+
///
85+
/// - [POSIX]
86+
///
87+
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/dirfd.html
88+
#[inline]
89+
#[doc(alias = "dirfd")]
90+
pub fn fd<'a>(&'a self) -> io::Result<BorrowedFd<'a>> {
91+
let raw_fd = unsafe { c::dirfd(self.libc_dir.as_ptr()) };
92+
if raw_fd < 0 {
93+
Err(io::Errno::last_os_error())
94+
} else {
95+
Ok(unsafe { BorrowedFd::borrow_raw(raw_fd) })
96+
}
97+
}
98+
7899
/// Borrow `fd` and construct a `Dir` that reads entries from the given
79100
/// directory file descriptor.
80101
#[inline]

src/backend/linux_raw/fs/dir.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,22 @@ impl Dir {
5050
})
5151
}
5252

53+
/// Returns the file descriptor associated with the directory stream.
54+
///
55+
/// The file descriptor is used internally by the directory stream. As a result, it is useful
56+
/// only for functions which do not depend or alter the file position.
57+
///
58+
/// # References
59+
///
60+
/// - [POSIX]
61+
///
62+
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/dirfd.html
63+
#[inline]
64+
#[doc(alias = "dirfd")]
65+
pub fn fd<'a>(&'a self) -> io::Result<BorrowedFd<'a>> {
66+
Ok(self.fd.as_fd())
67+
}
68+
5369
/// Borrow `fd` and construct a `Dir` that reads entries from the given
5470
/// directory file descriptor.
5571
#[inline]

0 commit comments

Comments
 (0)