use crate::error::Error;
use crate::error::Result;
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Threshold(f64);
impl Threshold {
pub const DEFAULT_SIMILARITY: Self = Self(0.9);
pub fn fraction(field: &'static str, value: f64) -> Result<Self> {
Self::share_of(field, value, 1.0, "a fraction between 0.0 and 1.0")
}
pub fn percent(field: &'static str, value: f64) -> Result<Self> {
Self::share_of(field, value, 100.0, "a percentage between 0.0 and 100.0")
}
fn share_of(
field: &'static str,
value: f64,
whole: f64,
expected: &'static str,
) -> Result<Self> {
if (0.0..=whole).contains(&value) {
Ok(Self(value / whole))
} else {
Err(Error::InvalidConfig {
field,
value: value.to_string(),
expected,
})
}
}
#[must_use]
pub const fn as_fraction(self) -> f64 {
self.0
}
#[must_use]
pub fn as_percent(self) -> f64 {
self.0 * 100.0
}
}