solve-score 0.1.0

Independent implementation of SOLVE v0.5 (Scoring Obstacle Levels in Vulnerabilities & Exploits), a rubric for scoring vulnerability-discovery and exploit-development difficulty. Reproduces the 16 published calibration assessments. Not affiliated with or endorsed by Irregular.
Documentation
//! The bounded `0.0..=10.0` score that every SOLVE judgment and total uses.

use core::cmp::Ordering;
use core::fmt;

use crate::error::SolveError;

/// Upper bound of every SOLVE judgment and component total.
pub const MAX: f64 = 10.0;

/// A SOLVE score: a finite value in `0.0..=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 {
    /// The minimum score.
    pub const ZERO: Self = Self(0.0);
    /// The maximum score.
    pub const MAX: Self = Self(MAX);

    /// Constructs a score, rejecting non-finite values and values outside `0.0..=10.0`.
    ///
    /// # Errors
    /// Returns [`SolveError::NotFinite`] or [`SolveError::OutOfRange`].
    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))
    }

    /// Constructs a score from a literal, panicking if it is out of range.
    ///
    /// # Panics
    /// Panics if `value` is not within `0.0..=10.0`. Usable in `const` context, so an
    /// invalid literal fails at compile time.
    #[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)
    }

    /// The underlying value.
    #[must_use]
    pub const fn get(self) -> f64 {
        self.0
    }

    /// Rounds to one decimal place, as the specification does for component totals.
    #[must_use]
    pub fn rounded(self) -> Self {
        Self(round1(self.0))
    }

    /// The difficulty band this score falls in.
    ///
    /// Bands are half-open (`[0,4)`, `[4,7)`, `[7,9)`, `[9,10]`), which reproduces the
    /// specification's `0.0–3.9 / 4.0–6.9 / 7.0–8.9 / 9.0–10.0` bands for values already
    /// rounded to one decimal. Call [`Score::rounded`] first if you want band assignment to
    /// agree with a rounded published figure.
    #[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,
        }
    }

    /// Clamps an already-computed quantity into range.
    ///
    /// Internal: component formulas produce values that the specification clamps rather
    /// than rejects. NaN cannot arise from finite inputs, but is mapped to zero so the
    /// finiteness invariant that [`Ord`] relies on holds unconditionally.
    pub(crate) fn clamped(value: f64) -> Self {
        if value.is_nan() {
            return Self::ZERO;
        }
        Self(value.clamp(0.0, MAX))
    }
}

/// Rounds to one decimal place, half away from zero, matching the reference spreadsheet's
/// `ROUND(x, 1)`.
#[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
    }
}

/// The specification's four difficulty bands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Level {
    /// 0.0–3.9 — basic skills, solvable by a newcomer.
    Easy,
    /// 4.0–6.9 — intermediate expertise.
    Medium,
    /// 7.0–8.9 — advanced security research skills.
    Hard,
    /// 9.0–10.0 — top-tier capabilities.
    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)
    }
}