use core::ffi::c_int;
use crate::error::Unspecified;
use core::fmt;
#[must_use = "You must handle the potential error"]
#[repr(transparent)]
pub struct Res(pub(crate) bool);
impl fmt::Debug for Res {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("Res {{ is_ok: {} }}", self.0 as u8))
}
}
impl Default for Res {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl Res {
pub const OK: Self = Self(true);
pub const ERR: Self = Self(false);
pub const fn new() -> Self { Self::OK }
#[inline]
pub const fn is_ok(&self) -> bool {
self.0
}
#[inline]
pub const fn is_err(&self) -> bool {
!self.0
}
#[inline]
pub fn check(&mut self, res: bool) {
self.0 &= res;
}
#[inline]
pub fn ensure_1(&mut self, res: c_int) {
self.0 &= (res as u8) == 1u8;
}
#[inline]
pub fn ensure_0(&mut self, res: c_int) {
self.0 &= (res as u8) == 0u8;
}
#[inline]
pub fn ensure_pos(&mut self, res: c_int) {
const R_SHR: c_int = (core::mem::size_of::<c_int>() * 8 - 1) as c_int;
self.0 &= (!(res >> R_SHR) as u8) & 1 == 1;
}
#[inline]
pub fn ensure(&mut self, res: Self) {
self.0 &= res.0;
}
#[allow(clippy::missing_errors_doc)]
#[inline(always)]
pub fn unit_err<OK>(self, ok: OK) -> Result<OK, Unspecified> {
if self.is_ok() {
Ok(ok)
} else {
Err(Unspecified)
}
}
#[inline(always)]
#[allow(clippy::missing_errors_doc)]
pub fn unit_err_with<F, OK>(self, ok: F) -> Result<OK, Unspecified>
where F: FnOnce() -> OK
{
if self.is_ok() {
Ok(ok())
} else {
Err(Unspecified)
}
}
#[inline]
#[track_caller]
pub fn unwrap(self) {
self.unit_err(()).unwrap();
}
}