use core::fmt;
#[derive(Debug)]
pub struct Certain(());
#[must_use = "the gated value must be handled"]
#[derive(Debug)]
pub enum Gate<T> {
HighConfidence(Certain, T),
Likely(T),
Unsure(T),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Thresholds {
likely: f64,
certain: f64,
}
impl Thresholds {
pub const MIN_CERTAIN: f64 = 0.95;
pub const DEFAULT: Self = Self {
likely: 0.60,
certain: Self::MIN_CERTAIN,
};
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 })
}
}
pub fn likely(self) -> f64 {
self.likely
}
pub fn certain(self) -> f64 {
self.certain
}
}
impl Default for Thresholds {
fn default() -> Self {
Self::DEFAULT
}
}
#[derive(Debug, Clone, Copy)]
pub struct InvalidThresholds {
pub likely: f64,
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 {}
#[derive(Debug, Clone, Copy)]
pub struct InvalidConfidence {
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 {}
#[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> {
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 })
}
}
pub fn confidence(&self) -> f64 {
self.p
}
pub fn gate(self) -> Gate<T> {
self.gate_with(Thresholds::DEFAULT)
}
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)
}
}
}