use crate::io::dma_file::{DmaFile, Result};
use std::io;
use std::path::Path;
#[derive(Clone, Debug)]
pub struct DmaOpenOptions {
read: bool,
pub(super) write: bool,
truncate: bool,
create: bool,
create_new: bool,
pub(super) custom_flags: libc::c_int,
pub(super) mode: libc::mode_t,
}
impl Default for DmaOpenOptions {
fn default() -> Self {
Self::new()
}
}
impl DmaOpenOptions {
pub fn new() -> Self {
Self {
read: false,
write: 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 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) {
(true, false) => libc::O_RDONLY,
(false, true) => libc::O_WRONLY,
(true, true) => libc::O_RDWR,
(false, false) => return Err(io::Error::from_raw_os_error(libc::EINVAL).into()),
})
}
pub(super) fn get_creation_mode(&self) -> Result<libc::c_int> {
if !self.write && (self.truncate || self.create || self.create_new) {
Err(io::Error::from_raw_os_error(libc::EINVAL).into())
} else {
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 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
}
}
#[cfg(test)]
mod test {
}