Skip to content

Commit 3ce3f2f

Browse files
cgwalterssunfishcode
authored andcommitted
fs::dir: Add a reopen_dir() method
In some cases when working with an existing C/C++ codebase already using `openat()` or other crates such as the `openat` crate, one may have an existing file descriptor and want to create a `cap-std` view of the same directory. Add an API which reopens from a source FD.
1 parent b2cf994 commit 3ce3f2f

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

cap-std/src/fs/dir.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -609,6 +609,20 @@ impl Dir {
609609
let _ = ambient_authority;
610610
fs::create_dir_all(path)
611611
}
612+
613+
/// Construct a new instance of `Self` from existing directory file descriptor.
614+
///
615+
/// This can be useful when interacting with other libraries and or C/C++ code
616+
/// which has invoked `openat(..., O_DIRECTORY)` external to this crate.
617+
#[cfg(not(windows))]
618+
pub fn reopen_dir(fd: BorrowedFd) -> io::Result<Self> {
619+
use io_lifetimes::AsFilelike;
620+
cap_primitives::fs::open_dir(
621+
&fd.as_filelike_view::<std::fs::File>(),
622+
std::path::Component::CurDir.as_ref(),
623+
)
624+
.map(Self::from_std_file)
625+
}
612626
}
613627

614628
#[cfg(not(windows))]

tests/fs_additional.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -847,3 +847,13 @@ fn maybe_dir() {
847847
// Opening directories works on all platforms with `maybe_dir`.
848848
check!(tmpdir.open_with("dir", OpenOptions::new().read(true).maybe_dir(true)));
849849
}
850+
851+
#[test]
852+
#[cfg(not(windows))]
853+
fn reopen_fd() {
854+
use rustix::fd::AsFd;
855+
let tmpdir = tmpdir();
856+
check!(tmpdir.create_dir("subdir"));
857+
let tmpdir2 = check!(cap_std::fs::Dir::reopen_dir(tmpdir.as_fd()));
858+
assert!(tmpdir2.exists("subdir"));
859+
}

0 commit comments

Comments
 (0)