use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ReturnCode {
Ok,
Error,
BadParameter,
Unsupported,
OutOfResources,
PreconditionNotMet,
}
impl ReturnCode {
#[must_use]
pub const fn is_ok(self) -> bool {
matches!(self, Self::Ok)
}
pub const fn into_result(self) -> Result<(), Self> {
match self {
Self::Ok => Ok(()),
other => Err(other),
}
}
}
impl fmt::Display for ReturnCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Ok => "OK",
Self::Error => "ERROR",
Self::BadParameter => "BAD_PARAMETER",
Self::Unsupported => "UNSUPPORTED",
Self::OutOfResources => "OUT_OF_RESOURCES",
Self::PreconditionNotMet => "PRECONDITION_NOT_MET",
})
}
}
#[cfg(feature = "std")]
impl std::error::Error for ReturnCode {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ok_is_ok_and_others_are_not() {
assert!(ReturnCode::Ok.is_ok());
for rc in [
ReturnCode::Error,
ReturnCode::BadParameter,
ReturnCode::Unsupported,
ReturnCode::OutOfResources,
ReturnCode::PreconditionNotMet,
] {
assert!(!rc.is_ok());
}
}
#[test]
fn into_result_maps_ok_to_unit_and_others_to_err() {
assert_eq!(ReturnCode::Ok.into_result(), Ok(()));
assert_eq!(
ReturnCode::PreconditionNotMet.into_result(),
Err(ReturnCode::PreconditionNotMet)
);
}
#[test]
fn display_reports_spec_token_names() {
assert_eq!(alloc::format!("{}", ReturnCode::Ok), "OK");
assert_eq!(
alloc::format!("{}", ReturnCode::PreconditionNotMet),
"PRECONDITION_NOT_MET"
);
assert_eq!(
alloc::format!("{}", ReturnCode::BadParameter),
"BAD_PARAMETER"
);
}
}