cap_primitives/fs/
reopen.rs

1//! Re-open a `fs::File` to produce an independent handle.
2
3use crate::fs::{is_file_read_write, is_same_file, reopen_impl, OpenOptions};
4use std::{fs, io};
5
6/// Re-open an `fs::File` to produce an independent handle.
7///
8/// This operation isn't supported by all operating systems in all
9/// circumstances, or in some operating systems in any circumstances,
10/// so it may return an `io::ErrorKind::Other` error if the file
11/// cannot be reopened.
12#[inline]
13pub fn reopen(file: &fs::File, options: &OpenOptions) -> io::Result<fs::File> {
14    let (read, write) = is_file_read_write(file)?;
15
16    // Don't grant more rights than the original file had. And don't allow
17    // it to create a file.
18    if options.create
19        || options.create_new
20        || (!read && options.read)
21        || (!write && (options.write || options.append || options.truncate))
22    {
23        return Err(io::Error::new(
24            io::ErrorKind::PermissionDenied,
25            "Couldn't reopen file",
26        ));
27    }
28
29    let new = reopen_impl(file, options)?;
30
31    if !is_same_file(file, &new)? {
32        return Err(io::Error::new(io::ErrorKind::Other, "Couldn't reopen file"));
33    }
34
35    Ok(new)
36}