From f749fe4d578ad30b6fff5f5abb10da0f9c30e6aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20Gibrowski=20Fa=C3=A9?= Date: Tue, 18 Nov 2025 15:21:15 -0300 Subject: [PATCH] Implement dirfd equivalent functions 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). --- src/backend/libc/fs/dir.rs | 21 +++++++++++++++++++++ src/backend/linux_raw/fs/dir.rs | 16 ++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/backend/libc/fs/dir.rs b/src/backend/libc/fs/dir.rs index fca90733e..3c4c3896b 100644 --- a/src/backend/libc/fs/dir.rs +++ b/src/backend/libc/fs/dir.rs @@ -75,6 +75,27 @@ impl Dir { } } + /// Returns the file descriptor associated with the directory stream. + /// + /// The file descriptor is used internally by the directory stream. As a result, it is useful + /// only for functions which do not depend or alter the file position. + /// + /// # References + /// + /// - [POSIX] + /// + /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/dirfd.html + #[inline] + #[doc(alias = "dirfd")] + pub fn fd<'a>(&'a self) -> io::Result> { + let raw_fd = unsafe { c::dirfd(self.libc_dir.as_ptr()) }; + if raw_fd < 0 { + Err(io::Errno::last_os_error()) + } else { + Ok(unsafe { BorrowedFd::borrow_raw(raw_fd) }) + } + } + /// Borrow `fd` and construct a `Dir` that reads entries from the given /// directory file descriptor. #[inline] diff --git a/src/backend/linux_raw/fs/dir.rs b/src/backend/linux_raw/fs/dir.rs index 31ebc5437..ef02b470f 100644 --- a/src/backend/linux_raw/fs/dir.rs +++ b/src/backend/linux_raw/fs/dir.rs @@ -50,6 +50,22 @@ impl Dir { }) } + /// Returns the file descriptor associated with the directory stream. + /// + /// The file descriptor is used internally by the directory stream. As a result, it is useful + /// only for functions which do not depend or alter the file position. + /// + /// # References + /// + /// - [POSIX] + /// + /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/dirfd.html + #[inline] + #[doc(alias = "dirfd")] + pub fn fd<'a>(&'a self) -> io::Result> { + Ok(self.fd.as_fd()) + } + /// Borrow `fd` and construct a `Dir` that reads entries from the given /// directory file descriptor. #[inline]