use core::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum WidthError {
ValueTooLarge {
value: u128,
bits: u32,
},
}
impl fmt::Display for WidthError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
WidthError::ValueTooLarge { value, bits } => {
write!(f, "value {value} does not fit in {bits} bits")
}
}
}
}
impl core::error::Error for WidthError {}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct UnknownDiscriminant {
pub value: u128,
pub type_name: &'static str,
}
impl UnknownDiscriminant {
#[must_use]
pub const fn new(value: u128, type_name: &'static str) -> Self {
Self { value, type_name }
}
}
impl fmt::Display for UnknownDiscriminant {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} has no variant for discriminant {}",
self.type_name, self.value
)
}
}
impl core::error::Error for UnknownDiscriminant {}
#[cfg(test)]
mod unit {
use super::*;
use alloc::string::ToString;
#[test]
fn value_too_large_carries_value_and_width() {
let e = WidthError::ValueTooLarge { value: 20, bits: 4 };
assert_eq!(e, WidthError::ValueTooLarge { value: 20, bits: 4 });
}
#[test]
fn value_too_large_display() {
let e = WidthError::ValueTooLarge { value: 20, bits: 4 };
assert_eq!(e.to_string(), "value 20 does not fit in 4 bits");
}
#[test]
fn unknown_discriminant_carries_value_and_name() {
let e = UnknownDiscriminant {
value: 9,
type_name: "Direction",
};
assert_eq!(e.value, 9);
assert_eq!(e.type_name, "Direction");
}
#[test]
fn unknown_discriminant_display() {
let e = UnknownDiscriminant {
value: 9,
type_name: "Direction",
};
assert_eq!(e.to_string(), "Direction has no variant for discriminant 9");
}
}