use std::sync::Arc;
#[derive(Debug, Clone, PartialEq)]
pub struct Suggestion<'a> {
pub candidate: &'a str,
pub score: f64,
}
pub trait Suggester: Send + Sync {
fn suggest<'a>(&self, query: &str, candidates: &'a [&str]) -> Vec<Suggestion<'a>>;
fn enrich_unknown(&self, query: &str, candidates: &[&str]) -> Option<String> {
let sugs = self.suggest(query, candidates);
if sugs.is_empty() {
return None;
}
let joined = sugs
.iter()
.take(3)
.map(|s| s.candidate)
.collect::<Vec<_>>()
.join(", ");
Some(format!("did you mean: {joined}"))
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopSuggester;
impl Suggester for NoopSuggester {
fn suggest<'a>(&self, _query: &str, _candidates: &'a [&str]) -> Vec<Suggestion<'a>> {
Vec::new()
}
fn enrich_unknown(&self, _query: &str, _candidates: &[&str]) -> Option<String> {
None
}
}
pub type SuggesterHandle = Arc<dyn Suggester>;
pub fn noop_handle() -> SuggesterHandle {
Arc::new(NoopSuggester)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn noop_returns_empty() {
let s = NoopSuggester;
assert!(s.suggest("foo", &["food", "for"]).is_empty());
assert_eq!(s.enrich_unknown("foo", &["food", "for"]), None);
}
#[test]
fn enrich_default_formats_top_three() {
struct FixedSuggester;
impl Suggester for FixedSuggester {
fn suggest<'a>(&self, _q: &str, cands: &'a [&str]) -> Vec<Suggestion<'a>> {
cands
.iter()
.enumerate()
.map(|(i, c)| Suggestion {
candidate: c,
score: 1.0 - (i as f64 * 0.1),
})
.collect()
}
}
let s = FixedSuggester;
let hint = s.enrich_unknown("q", &["a", "b", "c", "d", "e"]);
assert_eq!(hint.as_deref(), Some("did you mean: a, b, c"));
}
#[test]
fn noop_handle_is_shared() {
let h: SuggesterHandle = noop_handle();
assert!(h.suggest("x", &["y"]).is_empty());
}
}