use core::cmp::Ordering;
use core::fmt;
use crate::error::SolveError;
pub const MAX: f64 = 10.0;
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(try_from = "f64", into = "f64")
)]
pub struct Score(f64);
impl Score {
pub const ZERO: Self = Self(0.0);
pub const MAX: Self = Self(MAX);
pub fn new(value: f64) -> Result<Self, SolveError> {
if !value.is_finite() {
return Err(SolveError::NotFinite { value });
}
if !(0.0..=MAX).contains(&value) {
return Err(SolveError::OutOfRange { value });
}
Ok(Self(value))
}
#[must_use]
pub const fn lit(value: f64) -> Self {
assert!(
value >= 0.0 && value <= MAX,
"SOLVE score must be within 0.0..=10.0"
);
Self(value)
}
#[must_use]
pub const fn get(self) -> f64 {
self.0
}
#[must_use]
pub fn rounded(self) -> Self {
Self(round1(self.0))
}
#[must_use]
pub fn level(self) -> Level {
match self.0 {
v if v < 4.0 => Level::Easy,
v if v < 7.0 => Level::Medium,
v if v < 9.0 => Level::Hard,
_ => Level::Expert,
}
}
pub(crate) fn clamped(value: f64) -> Self {
if value.is_nan() {
return Self::ZERO;
}
Self(value.clamp(0.0, MAX))
}
}
#[must_use]
pub fn round1(value: f64) -> f64 {
(value * 10.0).round() / 10.0
}
impl Eq for Score {}
impl PartialOrd for Score {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Score {
fn cmp(&self, other: &Self) -> Ordering {
self.0
.partial_cmp(&other.0)
.expect("Score is finite by construction")
}
}
impl fmt::Display for Score {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:.1}", self.0)
}
}
impl TryFrom<f64> for Score {
type Error = SolveError;
fn try_from(value: f64) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl From<Score> for f64 {
fn from(score: Score) -> Self {
score.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Level {
Easy,
Medium,
Hard,
Expert,
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Self::Easy => "Easy",
Self::Medium => "Medium",
Self::Hard => "Hard",
Self::Expert => "Expert",
};
f.write_str(name)
}
}