use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Difficulty {
Easy,
#[default]
Medium,
Hard,
}
impl Difficulty {
pub const ALL: [Self; 3] = [Self::Easy, Self::Medium, Self::Hard];
pub const fn name(self) -> &'static str {
match self {
Self::Easy => "Easy",
Self::Medium => "Medium",
Self::Hard => "Hard",
}
}
#[must_use]
pub const fn next(self) -> Self {
match self {
Self::Easy => Self::Medium,
Self::Medium => Self::Hard,
Self::Hard => Self::Easy,
}
}
}
impl fmt::Display for Difficulty {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.name())
}
}
impl FromStr for Difficulty {
type Err = UnknownDifficulty;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::ALL
.into_iter()
.find(|level| level.name().eq_ignore_ascii_case(text))
.ok_or(UnknownDifficulty)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UnknownDifficulty;
impl fmt::Display for UnknownDifficulty {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("expected one of easy, medium or hard")
}
}
impl std::error::Error for UnknownDifficulty {}