cap_fs_ext/
reopen.rs

1use cap_primitives::fs::{reopen, OpenOptions};
2#[cfg(feature = "std")]
3use io_lifetimes::AsFilelike;
4use std::io;
5
6/// A trait for the `reopen` function.
7pub trait Reopen {
8    /// Re-open a file, producing a new independent handle.
9    ///
10    /// This operation isn't supported by all operating systems in all
11    /// circumstances, or in some operating systems in any circumstances, so it
12    /// may return an `io::ErrorKind::Other` error if the file cannot be
13    /// reopened.
14    ///
15    /// For files that aren't deleted, it's supported mostly-reliably on Linux
16    /// and Windows and somewhat-reliably on Darwin. Beyond that, it works
17    /// reliably on terminal device files and (slowly) on directories. It's not
18    /// possible to implement this operation with POSIX APIs alone (short of
19    /// traversing the entire filesystem), so further support will depend on
20    /// operating systems providing OS-specific APIs.
21    ///
22    /// This function takes an `OpenOptions`, however it does not acquire new
23    /// permissions that the original handle lacks.
24    fn reopen(&self, options: &OpenOptions) -> io::Result<Self>
25    where
26        Self: Sized;
27}
28
29impl Reopen for std::fs::File {
30    #[inline]
31    fn reopen(&self, options: &OpenOptions) -> io::Result<Self> {
32        reopen(self, options)
33    }
34}
35
36#[cfg(feature = "std")]
37impl Reopen for cap_std::fs::File {
38    #[inline]
39    fn reopen(&self, options: &OpenOptions) -> io::Result<Self> {
40        let file = reopen(
41            &AsFilelike::as_filelike_view::<std::fs::File>(self),
42            options,
43        )?;
44        Ok(Self::from_std(file))
45    }
46}
47
48#[cfg(all(feature = "std", feature = "fs_utf8"))]
49impl Reopen for cap_std::fs_utf8::File {
50    #[inline]
51    fn reopen(&self, options: &OpenOptions) -> io::Result<Self> {
52        let file = reopen(&self.as_filelike_view::<std::fs::File>(), options)?;
53        Ok(Self::from_std(file))
54    }
55}