Skip to main content

solve/
score.rs

1//! The bounded `0.0..=10.0` score that every SOLVE judgment and total uses.
2
3use core::cmp::Ordering;
4use core::fmt;
5
6use crate::error::SolveError;
7
8/// Upper bound of every SOLVE judgment and component total.
9pub const MAX: f64 = 10.0;
10
11/// A SOLVE score: a finite value in `0.0..=10.0`.
12#[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    /// The minimum score.
22    pub const ZERO: Self = Self(0.0);
23    /// The maximum score.
24    pub const MAX: Self = Self(MAX);
25
26    /// Constructs a score, rejecting non-finite values and values outside `0.0..=10.0`.
27    ///
28    /// # Errors
29    /// Returns [`SolveError::NotFinite`] or [`SolveError::OutOfRange`].
30    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    /// Constructs a score from a literal, panicking if it is out of range.
41    ///
42    /// # Panics
43    /// Panics if `value` is not within `0.0..=10.0`. Usable in `const` context, so an
44    /// invalid literal fails at compile time.
45    #[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    /// The underlying value.
55    #[must_use]
56    pub const fn get(self) -> f64 {
57        self.0
58    }
59
60    /// Rounds to one decimal place, as the specification does for component totals.
61    #[must_use]
62    pub fn rounded(self) -> Self {
63        Self(round1(self.0))
64    }
65
66    /// The difficulty band this score falls in.
67    ///
68    /// Bands are half-open (`[0,4)`, `[4,7)`, `[7,9)`, `[9,10]`), which reproduces the
69    /// specification's `0.0–3.9 / 4.0–6.9 / 7.0–8.9 / 9.0–10.0` bands for values already
70    /// rounded to one decimal. Call [`Score::rounded`] first if you want band assignment to
71    /// agree with a rounded published figure.
72    #[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    /// Clamps an already-computed quantity into range.
83    ///
84    /// Internal: component formulas produce values that the specification clamps rather
85    /// than rejects. NaN cannot arise from finite inputs, but is mapped to zero so the
86    /// finiteness invariant that [`Ord`] relies on holds unconditionally.
87    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/// Rounds to one decimal place, half away from zero, matching the reference spreadsheet's
96/// `ROUND(x, 1)`.
97#[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/// The specification's four difficulty bands.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
140#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
141pub enum Level {
142    /// 0.0–3.9 — basic skills, solvable by a newcomer.
143    Easy,
144    /// 4.0–6.9 — intermediate expertise.
145    Medium,
146    /// 7.0–8.9 — advanced security research skills.
147    Hard,
148    /// 9.0–10.0 — top-tier capabilities.
149    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}