#[cfg(feature = "std")]
extern crate std;
mod util;
pub const ERROR_CODE_OPTION_IS_NONE: i32 = 1;
pub const STR_OPTION_IS_NONE: &str = "Option is None.";
#[cfg(feature = "std")]
pub use std::error::Error as StdError;
#[cfg(not(feature = "std"))]
pub trait StdError: core::fmt::Debug + core::fmt::Display {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
None
}
}
pub trait OptionToResult<T, V> {
fn ok_or_(self) -> core::result::Result<T, Error<V>>;
}
#[derive(Debug, Clone)]
pub struct Error<V> {
error_value: V,
}
pub type Result<T, E = Error<String>> = core::result::Result<T, E>;
impl<V: core::fmt::Debug> core::fmt::Display for Error<V> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let type1 = core::any::type_name::<Self>(); let type3 = format!("{:?}", self);
write!(f, "{} :: {}", type1, type3)
}
}
impl<V: core::fmt::Debug> StdError for Error<V> {
}
impl<T> OptionToResult<T, String> for Option<T> {
fn ok_or_(self) -> Result<T> {
match self {
Some(v) => Ok(v),
None => Err(opt_is_none!()),
}
}
}
impl<V> Error<V> {
pub fn new(error_value: V) -> Self {
Self {
error_value,
}
}
pub fn error_value(&self) -> &V {
&self.error_value
}
}
macro_rules! impl_from_error_for {
($for_type:ty) => {
impl<V> From<Error<V>> for $for_type
where
V: Into<$for_type>,
{
fn from(value: Error<V>) -> Self {
value.error_value.into()
}
}
};
}
impl_from_error_for!(i32);
impl_from_error_for!(u32);
impl_from_error_for!(String);
#[cfg(not(feature = "std"))]
impl<V: core::fmt::Debug + 'static> From<Error<V>> for Box<dyn StdError> {
fn from(value: Error<V>) -> Self {
Box::new(value)
}
}