use core::fmt;
use crate::Position;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
Next,
Previous,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PositionError {
InvalidCharacter {
character: char,
index: usize,
},
Overflow {
position: Position,
length: usize,
limit: usize,
},
EdgeReached {
position: Position,
direction: Direction,
},
ThresholdReached {
position: Position,
length: usize,
threshold: usize,
},
SystemMismatch {
position: Position,
},
}
impl PositionError {
pub fn is_overflow(&self) -> bool {
matches!(self, Self::Overflow { .. } | Self::EdgeReached { .. })
}
pub fn is_dangerous(&self) -> bool {
matches!(self, Self::ThresholdReached { .. })
}
pub fn is_mismatch(&self) -> bool {
matches!(self, Self::SystemMismatch { .. })
}
pub fn is_invalid(&self) -> bool {
matches!(self, Self::InvalidCharacter { .. })
}
pub fn position(&self) -> Option<&Position> {
match self {
Self::EdgeReached { position, .. }
| Self::Overflow { position, .. }
| Self::ThresholdReached { position, .. }
| Self::SystemMismatch { position } => Some(position),
Self::InvalidCharacter { .. } => None,
}
}
}
impl fmt::Display for PositionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidCharacter { character, index } => write!(
f,
"The character '{character}' at index {index} is not a digit of the system (the zero or a character from first to last)."
),
Self::Overflow {
position,
length,
limit,
} => {
write!(f, "The position \"{position}")?;
if *length > position.len() {
f.write_str("...")?;
}
write!(
f,
"\" caused an overflow as its length '{length}' is bigger than the allowed system length '{limit}'."
)
}
Self::EdgeReached {
position,
direction,
} => {
let (direction, edge) = match direction {
Direction::Next => ("next", "last"),
Direction::Previous => ("previous", "first"),
};
write!(
f,
"The position \"{position}\" has no {direction} value as its 'n' section is already the {edge} value of the system."
)
}
Self::ThresholdReached {
position,
length,
threshold,
} => write!(
f,
"The position \"{position}\" with '{length}' reached the threshold '{threshold}'."
),
Self::SystemMismatch { position } => write!(
f,
"The position \"{position}\" was created by a system with a different configuration, positions of different systems can't be mixed."
),
}
}
}
impl std::error::Error for PositionError {}