Skip to content

Commit e0bc267

Browse files
committed
Auto merge of #76110 - FedericoPonzi:convert-openoptions-cint, r=JoshTriplett
Function to convert OpenOptions to c_int Fixes: #74943 The creation_mode and access_mode function were already available in the OpenOptions struct, but currently private. I've added a new free functions to unix/fs.rs which takes the OpenOptions, and returns the c_int to be used as parameter for the `open` call.
2 parents cbc5e4d + 2f51922 commit e0bc267

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

library/std/src/sys/unix/ext/fs.rs

+29
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,31 @@ pub trait OpenOptionsExt {
348348
/// ```
349349
#[stable(feature = "open_options_ext", since = "1.10.0")]
350350
fn custom_flags(&mut self, flags: i32) -> &mut Self;
351+
352+
/// Get the flags as [`libc::c_int`].
353+
///
354+
/// This method allows the reuse of the OpenOptions as flags argument for [`libc::open`].
355+
///
356+
/// [`libc::c_int`]: https://docs.rs/libc/*/libc/type.c_int.html
357+
/// [`libc::open`]: https://docs.rs/libc/*/libc/fn.open.html
358+
///
359+
/// # Examples
360+
///
361+
/// ```no_run
362+
/// # #![feature(rustc_private)]
363+
/// #![feature(open_options_ext_as_flags)]
364+
/// extern crate libc;
365+
/// use std::ffi::CString;
366+
/// use std::fs::OpenOptions;
367+
/// use std::os::unix::fs::OpenOptionsExt;
368+
///
369+
/// let mut options = OpenOptions::new();
370+
/// options.write(true).read(true);
371+
/// let file_name = CString::new("foo.txt").unwrap();
372+
/// let file = unsafe { libc::open(file_name.as_c_str().as_ptr(), options.as_flags().unwrap()) };
373+
/// ```
374+
#[unstable(feature = "open_options_ext_as_flags", issue = "76801")]
375+
fn as_flags(&self) -> io::Result<libc::c_int>;
351376
}
352377

353378
#[stable(feature = "fs_ext", since = "1.1.0")]
@@ -361,6 +386,10 @@ impl OpenOptionsExt for OpenOptions {
361386
self.as_inner_mut().custom_flags(flags);
362387
self
363388
}
389+
390+
fn as_flags(&self) -> io::Result<libc::c_int> {
391+
self.as_inner().as_flags()
392+
}
364393
}
365394

366395
/// Unix-specific extensions to [`fs::Metadata`].

library/std/src/sys/unix/fs.rs

+6
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,12 @@ impl OpenOptions {
656656
self.mode = mode as mode_t;
657657
}
658658

659+
pub fn as_flags(&self) -> io::Result<c_int> {
660+
let access_mode = self.get_access_mode()?;
661+
let creation_mode = self.get_creation_mode()?;
662+
Ok(creation_mode | access_mode | self.custom_flags)
663+
}
664+
659665
fn get_access_mode(&self) -> io::Result<c_int> {
660666
match (self.read, self.write, self.append) {
661667
(true, false, false) => Ok(libc::O_RDONLY),

0 commit comments

Comments
 (0)