requisite 0.1.0

Data-handling requirements encoded in Rust types.
Documentation
//! Confidence-based action gates.
//!
//! [`Confident<T>`] carries a value and a validated probability.
//! [`Confident::gate`] applies the default tier boundaries, while
//! [`Confident::gate_with`] accepts application-defined [`Thresholds`].
//!
//! The highest tier also carries a [`Certain`] token. Functions can require this
//! token to make a successful high-confidence check part of their call
//! contract.

use core::fmt;

/// Proof that [`Confident::gate`] selected the highest confidence tier.
#[derive(Debug)]
pub struct Certain(());

/// A value classified by confidence tier.
#[must_use = "the gated value must be handled"]
#[derive(Debug)]
pub enum Gate<T> {
    /// Confidence meets the certain threshold. Includes a [`Certain`] token.
    HighConfidence(Certain, T),
    /// Confidence meets the likely threshold.
    Likely(T),
    /// Confidence is below the likely threshold.
    Unsure(T),
}

/// Valid confidence boundaries for [`Confident::gate_with`].
///
/// The likely threshold must be lower than the certain threshold. Both values
/// must be finite probabilities, and the certain threshold must preserve the
/// [`Certain`] token's minimum confidence.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Thresholds {
    likely: f64,
    certain: f64,
}

impl Thresholds {
    /// Minimum confidence represented by a [`Certain`] token.
    pub const MIN_CERTAIN: f64 = 0.95;

    /// The boundaries used by [`Confident::gate`].
    pub const DEFAULT: Self = Self {
        likely: 0.60,
        certain: Self::MIN_CERTAIN,
    };

    /// Validate confidence boundaries.
    pub fn new(likely: f64, certain: f64) -> Result<Self, InvalidThresholds> {
        if likely.is_finite()
            && certain.is_finite()
            && (0.0..=1.0).contains(&likely)
            && (0.0..=1.0).contains(&certain)
            && certain >= Self::MIN_CERTAIN
            && likely < certain
        {
            Ok(Self { likely, certain })
        } else {
            Err(InvalidThresholds { likely, certain })
        }
    }

    /// Return the lower boundary for [`Gate::Likely`].
    pub fn likely(self) -> f64 {
        self.likely
    }

    /// Return the lower boundary for [`Gate::HighConfidence`].
    pub fn certain(self) -> f64 {
        self.certain
    }
}

impl Default for Thresholds {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Error returned when confidence boundaries are invalid.
#[derive(Debug, Clone, Copy)]
pub struct InvalidThresholds {
    /// Requested lower boundary for [`Gate::Likely`].
    pub likely: f64,
    /// Requested lower boundary for [`Gate::HighConfidence`].
    pub certain: f64,
}

impl fmt::Display for InvalidThresholds {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "confidence thresholds must be finite values in 0.0..=1.0 with likely < certain and certain >= {}; got likely={} and certain={}",
            Thresholds::MIN_CERTAIN, self.likely, self.certain
        )
    }
}

impl std::error::Error for InvalidThresholds {}

/// Error returned when a confidence is outside `0.0..=1.0` or non-finite.
#[derive(Debug, Clone, Copy)]
pub struct InvalidConfidence {
    /// The rejected confidence.
    pub value: f64,
}

impl fmt::Display for InvalidConfidence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "confidence must be a finite value in 0.0..=1.0; got {}",
            self.value
        )
    }
}

impl std::error::Error for InvalidConfidence {}

/// A value carried together with how confident you are in it (`0.0..=1.0`).
#[must_use = "the confidence-tagged value must be gated or otherwise consumed"]
#[derive(Debug)]
pub struct Confident<T> {
    val: T,
    p: f64,
}

impl<T> Confident<T> {
    /// Attach a validated confidence to a value.
    ///
    /// Returns [`InvalidConfidence`] for non-finite values or values outside
    /// `0.0..=1.0`.
    pub fn new(val: T, p: f64) -> Result<Self, InvalidConfidence> {
        if p.is_finite() && (0.0..=1.0).contains(&p) {
            Ok(Confident { val, p })
        } else {
            Err(InvalidConfidence { value: p })
        }
    }

    /// Read the confidence.
    pub fn confidence(&self) -> f64 {
        self.p
    }

    /// Classify the value by confidence tier.
    ///
    /// The highest tier includes a [`Certain`] token with the value.
    pub fn gate(self) -> Gate<T> {
        self.gate_with(Thresholds::DEFAULT)
    }

    /// Classify the value using application-defined confidence boundaries.
    pub fn gate_with(self, thresholds: Thresholds) -> Gate<T> {
        if self.p >= thresholds.certain {
            Gate::HighConfidence(Certain(()), self.val)
        } else if self.p >= thresholds.likely {
            Gate::Likely(self.val)
        } else {
            Gate::Unsure(self.val)
        }
    }
}