atomic_write_file/
dir.rs

1use crate::imp;
2
3/// A borrowed reference to the directory containing an
4/// [`AtomicWriteFile`](crate::AtomicWriteFile).
5///
6/// This can be obtained via [`AtomicWriteFile::directory()`](crate::AtomicWriteFile::directory).
7/// The purpose of this struct is to allow you to obtain the directory file descriptor, without
8/// having to open it through a call to `open(2)`.
9///
10/// This struct supports only two operations:
11/// - conversion to a borrowed directory file descriptor through
12///   [`AsFd::as_fd()`](std::os::fd::AsFd::as_fd)
13/// - conversion to a raw directory file descriptor through
14///   [`AsRawFd::as_raw_fd()`](std::os::fd::AsRawFd::as_raw_fd)
15///
16/// Directory file descriptors are not available on all platforms. See
17/// [`AtomicWriteFile::directory()`](crate::AtomicWriteFile::directory) for more details.
18///
19/// # Examples
20///
21/// ```
22/// # fn main() -> std::io::Result<()> {
23/// # let test_dir = option_env!("TEST_DIR").unwrap_or("target/test-files");
24/// # std::fs::create_dir_all(&test_dir).expect("failed to create test dir");
25/// # std::env::set_current_dir(test_dir).expect("failed to move to test dir");
26/// # #[cfg(any(unix, target_os = "wasi"))]
27/// use std::os::fd::AsFd;
28/// use atomic_write_file::AtomicWriteFile;
29///
30/// let file = AtomicWriteFile::open("foo.txt")?;
31/// if let Some(dir) = file.directory() {
32/// #   #[cfg(any(unix, target_os = "wasi"))]
33///     let borrowed_fd = dir.as_fd();
34/// #   #[cfg(any(unix, target_os = "wasi"))]
35///     println!("directory fd: {:?}", borrowed_fd);
36/// #   #[cfg(not(any(unix, target_os = "wasi")))]
37/// #   let _ = dir;
38/// }
39/// # Ok(())
40/// # }
41/// ```
42#[derive(Copy, Clone, Debug)]
43pub struct Directory<'a> {
44    #[cfg_attr(not(any(unix, target_os = "wasi")), allow(dead_code))]
45    inner: &'a imp::Dir,
46}
47
48impl<'a> Directory<'a> {
49    pub(crate) fn new(inner: &'a imp::Dir) -> Self {
50        Self { inner }
51    }
52}
53
54#[cfg(any(unix, target_os = "wasi"))]
55impl std::os::fd::AsFd for Directory<'_> {
56    #[inline]
57    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
58        self.inner.as_fd()
59    }
60}
61
62#[cfg(any(unix, target_os = "wasi"))]
63impl std::os::fd::AsRawFd for Directory<'_> {
64    #[inline]
65    fn as_raw_fd(&self) -> std::os::fd::RawFd {
66        self.inner.as_raw_fd()
67    }
68}