pub type Result<T> = core::result::Result<T, Error>;
pub const EINVAL: i32 = 22;
pub const NEINVAL: i32 = -EINVAL;
pub const EILSEQ: i32 = 84;
pub const NEILSEQ: i32 = -EILSEQ;
pub const ETIMEDOUT: i32 = 110;
pub const NETIMEDOUT: i32 = -ETIMEDOUT;
pub const ENOMEDIUM: i32 = 123;
pub const NENOMEDIUM: i32 = -ENOMEDIUM;
#[repr(i32)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Error {
#[default]
None = 0,
Invalid = 22,
IllegalSequence = 84,
TimedOut = 110,
NoMedium = 123,
InvalidVariant(usize),
InvalidFieldVariant { field: &'static str, value: usize },
InvalidValue {
value: usize,
min: usize,
max: usize,
},
InvalidFieldValue {
field: &'static str,
value: usize,
min: usize,
max: usize,
},
InvalidCrc7 { invalid: u8, calculated: u8 },
InvalidLength { len: usize, expected: usize },
}
impl Error {
pub const fn invalid_field_variant(field: &'static str, value: usize) -> Self {
Self::InvalidFieldVariant { field, value }
}
pub const fn invalid_field_value(
field: &'static str,
value: usize,
min: usize,
max: usize,
) -> Self {
Self::InvalidFieldValue {
field,
value,
min,
max,
}
}
pub const fn invalid_crc7(invalid: u8, calculated: u8) -> Self {
Self::InvalidCrc7 {
invalid,
calculated,
}
}
pub const fn invalid_length(len: usize, expected: usize) -> Self {
Self::InvalidLength { len, expected }
}
pub const fn from_i32(val: i32) -> Option<Self> {
match val {
EINVAL | NEINVAL => Some(Self::Invalid),
EILSEQ | NEILSEQ => Some(Self::IllegalSequence),
ETIMEDOUT | NETIMEDOUT => Some(Self::TimedOut),
ENOMEDIUM | NENOMEDIUM => Some(Self::NoMedium),
_ => None,
}
}
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::None => write!(f, "unknown error"),
Self::Invalid => write!(f, "invalid error"),
Self::IllegalSequence => write!(f, "illegal command sequence"),
Self::TimedOut => write!(f, "timed out"),
Self::NoMedium => write!(f, "no medium"),
Self::InvalidVariant(err) => write!(f, "invalid enum variant: {err}"),
Self::InvalidFieldVariant { field, value } => {
write!(f, "invalid field: {field}, enum variant: {value}")
}
Self::InvalidValue { value, min, max } => {
write!(f, "invalid value: {value}, min: {min}, max: {max}")
}
Self::InvalidFieldValue {
field,
value,
min,
max,
} => {
write!(
f,
"invalid field: {field}, value: {value}, min: {min}, max: {max}"
)
}
Self::InvalidCrc7 {
invalid,
calculated,
} => write!(f, "invalid CRC-7: {invalid}, expected: {calculated}"),
Self::InvalidLength { len, expected } => {
write!(f, "invalid structure length: {len}, expected: {expected}")
}
}
}
}
impl core::error::Error for Error {}