#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OverflowError {
what: &'static str,
value: Option<usize>,
type_name: &'static str,
}
impl OverflowError {
pub fn new<T>(what: &'static str) -> Self {
Self {
what,
value: None,
type_name: std::any::type_name::<T>(),
}
}
pub const fn with_value(mut self, value: usize) -> Self {
self.value = Some(value);
self
}
pub const fn what(&self) -> &'static str {
self.what
}
pub const fn value(&self) -> Option<usize> {
self.value
}
pub const fn type_name(&self) -> &'static str {
self.type_name
}
}
impl std::fmt::Display for OverflowError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self {
what,
value,
type_name,
} = self;
write!(f, "{what} overflow: ")?;
match value {
Some(value) => write!(f, "{value} does not fit in {type_name}"),
None => write!(f, "does not fit in {type_name}"),
}
}
}
impl std::error::Error for OverflowError {}