1use core::cmp::Ordering;
4use core::fmt;
5
6use crate::error::SolveError;
7
8pub const MAX: f64 = 10.0;
10
11#[derive(Debug, Clone, Copy, PartialEq)]
13#[cfg_attr(
14 feature = "serde",
15 derive(serde::Serialize, serde::Deserialize),
16 serde(try_from = "f64", into = "f64")
17)]
18pub struct Score(f64);
19
20impl Score {
21 pub const ZERO: Self = Self(0.0);
23 pub const MAX: Self = Self(MAX);
25
26 pub fn new(value: f64) -> Result<Self, SolveError> {
31 if !value.is_finite() {
32 return Err(SolveError::NotFinite { value });
33 }
34 if !(0.0..=MAX).contains(&value) {
35 return Err(SolveError::OutOfRange { value });
36 }
37 Ok(Self(value))
38 }
39
40 #[must_use]
46 pub const fn lit(value: f64) -> Self {
47 assert!(
48 value >= 0.0 && value <= MAX,
49 "SOLVE score must be within 0.0..=10.0"
50 );
51 Self(value)
52 }
53
54 #[must_use]
56 pub const fn get(self) -> f64 {
57 self.0
58 }
59
60 #[must_use]
62 pub fn rounded(self) -> Self {
63 Self(round1(self.0))
64 }
65
66 #[must_use]
73 pub fn level(self) -> Level {
74 match self.0 {
75 v if v < 4.0 => Level::Easy,
76 v if v < 7.0 => Level::Medium,
77 v if v < 9.0 => Level::Hard,
78 _ => Level::Expert,
79 }
80 }
81
82 pub(crate) fn clamped(value: f64) -> Self {
88 if value.is_nan() {
89 return Self::ZERO;
90 }
91 Self(value.clamp(0.0, MAX))
92 }
93}
94
95#[must_use]
98pub fn round1(value: f64) -> f64 {
99 (value * 10.0).round() / 10.0
100}
101
102impl Eq for Score {}
103
104impl PartialOrd for Score {
105 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
106 Some(self.cmp(other))
107 }
108}
109
110impl Ord for Score {
111 fn cmp(&self, other: &Self) -> Ordering {
112 self.0
113 .partial_cmp(&other.0)
114 .expect("Score is finite by construction")
115 }
116}
117
118impl fmt::Display for Score {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 write!(f, "{:.1}", self.0)
121 }
122}
123
124impl TryFrom<f64> for Score {
125 type Error = SolveError;
126
127 fn try_from(value: f64) -> Result<Self, Self::Error> {
128 Self::new(value)
129 }
130}
131
132impl From<Score> for f64 {
133 fn from(score: Score) -> Self {
134 score.0
135 }
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
140#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
141pub enum Level {
142 Easy,
144 Medium,
146 Hard,
148 Expert,
150}
151
152impl fmt::Display for Level {
153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 let name = match self {
155 Self::Easy => "Easy",
156 Self::Medium => "Medium",
157 Self::Hard => "Hard",
158 Self::Expert => "Expert",
159 };
160 f.write_str(name)
161 }
162}