use crate::errors::QuadbinError;
use core::fmt;
const MAX: u8 = 4;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[repr(u8)]
pub enum Direction {
Up = 0,
Right = 1,
Left = 2,
Down = 3,
}
impl Direction {
pub fn iter() -> impl Iterator<Item = Self> {
(0..=MAX).map(Self::new_unchecked)
}
#[expect(unsafe_code, reason = "only used internally")]
pub(crate) const fn new_unchecked(value: u8) -> Self {
assert!(value <= MAX, "direction out of range");
unsafe { core::mem::transmute::<u8, Self>(value) }
}
}
impl TryFrom<u8> for Direction {
type Error = QuadbinError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(Self::Up),
1 => Ok(Self::Right),
2 => Ok(Self::Left),
3 => Ok(Self::Down),
_ => Err(Self::Error::InvalidDirection(value)),
}
}
}
impl From<Direction> for u8 {
fn from(value: Direction) -> Self {
value as Self
}
}
impl From<Direction> for u64 {
fn from(value: Direction) -> Self {
u8::from(value).into()
}
}
impl From<Direction> for usize {
fn from(value: Direction) -> Self {
u8::from(value).into()
}
}
impl fmt::Display for Direction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", u8::from(*self))
}
}