use crate::hio::errors::HioError;
use std::fs::{File, OpenOptions};
use std::io;
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;
#[cfg(unix)]
pub fn ocfn<P: AsRef<Path>>(
path: P,
read: bool,
write: bool,
append: bool,
truncate: bool,
create: bool,
create_new: bool,
perm: u32,
) -> Result<File, HioError> {
let path = path.as_ref();
if create {
let create_result = OpenOptions::new()
.read(read)
.write(write)
.append(append)
.truncate(false) .create_new(true) .mode(perm)
.open(path);
match create_result {
Ok(file) => return Ok(file),
Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => {
if create_new {
return Err(HioError::FilerError(format!(
"File already exists: {}",
path.display()
)));
}
}
Err(e) => return Err(HioError::IoError(e)),
}
}
let file = OpenOptions::new()
.read(read)
.write(write)
.append(append)
.truncate(truncate)
.create(create && !create_new)
.mode(perm)
.open(path)
.map_err(HioError::IoError)?;
Ok(file)
}