use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
use crate::normalize::Normalizer;
use crate::similarity::Weights;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
pub normalizer: Normalizer,
pub weights: Weights,
pub equal_threshold: f64,
pub align_floor: f64,
}
impl Default for Config {
fn default() -> Self {
Config {
normalizer: Normalizer::default(),
weights: Weights::default(),
equal_threshold: 0.999,
align_floor: 0.4,
}
}
}
impl Config {
pub fn validate(&self) -> Result<()> {
for (name, v) in [
("equal_threshold", self.equal_threshold),
("align_floor", self.align_floor),
] {
if !(0.0..=1.0).contains(&v) {
return Err(Error::Config(format!("{name} must be in [0, 1], got {v}")));
}
}
if self.align_floor > self.equal_threshold {
return Err(Error::Config(
"align_floor must not exceed equal_threshold".into(),
));
}
Ok(())
}
pub fn from_json_str(s: &str) -> Result<Self> {
let cfg: Config = serde_json::from_str(s)?;
cfg.validate()?;
Ok(cfg)
}
#[cfg(feature = "cli")]
pub fn from_toml_str(s: &str) -> Result<Self> {
let cfg: Config =
toml::from_str(s).map_err(|e| Error::Config(format!("invalid TOML: {e}")))?;
cfg.validate()?;
Ok(cfg)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_validate() {
Config::default().validate().unwrap();
}
#[test]
fn out_of_range_threshold_is_rejected() {
let cfg = Config {
equal_threshold: 1.5,
..Config::default()
};
assert!(cfg.validate().is_err());
}
#[test]
fn floor_above_equal_is_rejected() {
let cfg = Config {
align_floor: 0.99,
equal_threshold: 0.5,
..Config::default()
};
assert!(cfg.validate().is_err());
}
#[test]
fn roundtrips_through_json() {
let cfg = Config::default();
let s = serde_json::to_string(&cfg).unwrap();
let back = Config::from_json_str(&s).unwrap();
assert_eq!(cfg, back);
}
}