From 1bc0627607262cc60a7692b16e205f30fc88b89f Mon Sep 17 00:00:00 2001 From: Federico Ponzi Date: Mon, 31 Aug 2020 15:48:28 +0200 Subject: [PATCH] Add as_flag function to the OpenOptionsExt struct --- library/std/src/sys/unix/ext/fs.rs | 30 ++++++++++++++++++++++++++++++ library/std/src/sys/unix/fs.rs | 12 +++++------- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/library/std/src/sys/unix/ext/fs.rs b/library/std/src/sys/unix/ext/fs.rs index b590a0280d1..0a00c64e6c5 100644 --- a/library/std/src/sys/unix/ext/fs.rs +++ b/library/std/src/sys/unix/ext/fs.rs @@ -345,6 +345,33 @@ pub trait OpenOptionsExt { /// ``` #[stable(feature = "open_options_ext", since = "1.10.0")] fn custom_flags(&mut self, flags: i32) -> &mut Self; + + /// Get the flags of this OpenOptions as libc::c_int. + /// + /// This method allows the reuse of the OpenOptions as flags argument for `libc::open()`. + /// + /// # Examples + /// + /// ```no_run + /// # #![feature(rustc_private)] + /// extern crate libc; + /// use std::ffi::CString; + /// use std::fs::OpenOptions; + /// use std::os::unix::fs::OpenOptionsExt; + /// + /// # fn main() { + /// let mut options = OpenOptions::new(); + /// options.write(true).read(true); + /// if cfg!(unix) { + /// options.custom_flags(libc::O_NOFOLLOW); + /// } + /// let file_name = CString::new("foo.txt").unwrap(); + /// let file = unsafe{ libc::open(file_name.as_c_str().as_ptr(), options.as_flags().unwrap()) }; + /// + /// # } + /// ``` + #[stable(feature = "open_options_ext_as_flags", since = "1.47.0")] + fn as_flags(&self) -> io::Result; } #[stable(feature = "fs_ext", since = "1.1.0")] @@ -358,6 +385,9 @@ impl OpenOptionsExt for OpenOptions { self.as_inner_mut().custom_flags(flags); self } + fn as_flags(&self) -> io::Result { + self.as_inner().as_flags() + } } /// Unix-specific extensions to [`fs::Metadata`]. diff --git a/library/std/src/sys/unix/fs.rs b/library/std/src/sys/unix/fs.rs index 59dfd9f9dc4..f4d3ad2d2a4 100644 --- a/library/std/src/sys/unix/fs.rs +++ b/library/std/src/sys/unix/fs.rs @@ -655,7 +655,11 @@ impl OpenOptions { pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; } - + pub fn as_flags(&self) -> io::Result { + let access_mode = self.get_access_mode()?; + let creation_mode = self.get_creation_mode()?; + Ok(creation_mode | access_mode | self.custom_flags) + } fn get_access_mode(&self) -> io::Result { match (self.read, self.write, self.append) { (true, false, false) => Ok(libc::O_RDONLY), @@ -692,7 +696,6 @@ impl OpenOptions { } } - impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result { let path = cstr(path)?; @@ -963,11 +966,6 @@ pub fn rename(old: &Path, new: &Path) -> io::Result<()> { Ok(()) } -pub fn get_openopetions_as_cint(from: OpenOptions) -> io::Result { - let access_mode = from.get_access_mode()?; - let creation_mode = from.get_creation_mode()?; - Ok(creation_mode | access_mode) -} pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { let p = cstr(p)?;