use std::{
error::Error,
ffi::CStr,
fmt,
os::fd::{FromRawFd, OwnedFd},
};
#[derive(Clone, Copy, Debug)]
pub enum DescriptorError {
OpenFail,
CloseFail,
}
impl fmt::Display for DescriptorError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", ::errno::errno())
}
}
impl Error for DescriptorError {
fn description(&self) -> &str {
match *self {
DescriptorError::OpenFail => "can't open the fd",
DescriptorError::CloseFail => "can't close the fd",
}
}
fn cause(&self) -> Option<&dyn Error> {
None
}
}
pub fn open(
path: &CStr,
flag: libc::c_int,
mode: Option<libc::c_int>,
) -> Result<OwnedFd, DescriptorError> {
unsafe {
match libc::open(path.as_ptr().cast(), flag, mode.unwrap_or_default()) {
-1 => Err(DescriptorError::OpenFail),
fd => Ok(OwnedFd::from_raw_fd(fd)),
}
}
}