use crate::io::{
dma_file::{DmaFile, Result},
BufferedFile,
};
use std::{io, path::Path};
#[derive(Clone, Debug)]
pub struct OpenOptions {
read: bool,
pub(super) write: bool,
append: bool,
truncate: bool,
create: bool,
create_new: bool,
pub(super) custom_flags: libc::c_int,
pub(super) mode: libc::mode_t,
}
impl Default for OpenOptions {
fn default() -> Self {
Self::new()
}
}
impl OpenOptions {
pub fn new() -> Self {
Self {
read: false,
write: false,
append: false,
truncate: false,
create: false,
create_new: false,
custom_flags: 0,
mode: 0o666,
}
}
pub fn read(&mut self, read: bool) -> &mut Self {
self.read = read;
self
}
pub fn write(&mut self, write: bool) -> &mut Self {
self.write = write;
self
}
pub fn append(&mut self, append: bool) -> &mut Self {
self.append = append;
self
}
pub fn truncate(&mut self, truncate: bool) -> &mut Self {
self.truncate = truncate;
self
}
pub fn create(&mut self, create: bool) -> &mut Self {
self.create = create;
self
}
pub fn create_new(&mut self, create_new: bool) -> &mut Self {
self.create_new = create_new;
self
}
pub fn custom_flags(&mut self, flags: i32) -> &mut Self {
self.custom_flags = flags;
self
}
pub fn mode(&mut self, mode: libc::mode_t) -> &mut Self {
self.mode = mode;
self
}
pub(super) fn get_access_mode(&self) -> Result<libc::c_int> {
Ok(match (self.read, self.write, self.append) {
(true, false, false) => libc::O_RDONLY,
(false, true, false) => libc::O_WRONLY,
(true, true, false) => libc::O_RDWR,
(false, _, true) => libc::O_WRONLY | libc::O_APPEND,
(true, _, true) => libc::O_RDWR | libc::O_APPEND,
(false, false, false) => return Err(io::Error::from_raw_os_error(libc::EINVAL).into()),
})
}
pub(super) fn get_creation_mode(&self) -> Result<libc::c_int> {
match (self.write, self.append) {
(true, false) => {}
(false, false) => {
if self.truncate || self.create || self.create_new {
return Err(io::Error::from_raw_os_error(libc::EINVAL).into());
}
}
(_, true) => {
if self.truncate && !self.create_new {
return Err(io::Error::from_raw_os_error(libc::EINVAL).into());
}
}
}
Ok(match (self.create, self.truncate, self.create_new) {
(false, false, false) => 0,
(true, false, false) => libc::O_CREAT,
(false, true, false) => libc::O_TRUNC,
(true, true, false) => libc::O_CREAT | libc::O_TRUNC,
(_, _, true) => libc::O_CREAT | libc::O_EXCL,
})
}
pub async fn dma_open<P: AsRef<Path>>(&self, path: P) -> Result<DmaFile> {
DmaFile::open_with_options(
-1_i32,
path.as_ref(),
if self.create || self.create_new {
"Creating"
} else {
"Opening"
},
self,
)
.await
}
pub async fn buffered_open<P: AsRef<Path>>(&self, path: P) -> Result<BufferedFile> {
BufferedFile::open_with_options(
-1_i32,
path.as_ref(),
if self.create || self.create_new {
"Creating"
} else {
"Opening"
},
self,
)
.await
}
}
#[cfg(test)]
mod test {
}