use regex::Regex;
use std::sync::OnceLock;
#[derive(Debug)]
pub struct Pattern {
pub name: &'static str,
regex: OnceLock<Regex>,
pattern: &'static str,
pub confidence: f32,
}
impl Pattern {
pub const fn new(name: &'static str, pattern: &'static str, confidence: f32) -> Self {
Self {
name,
regex: OnceLock::new(),
pattern,
confidence,
}
}
fn compiled(&self) -> &Regex {
self.regex
.get_or_init(|| Regex::new(self.pattern).expect("invalid regex"))
}
pub fn matches(&self, text: &str) -> bool {
self.compiled().is_match(text)
}
pub fn captures(&self, text: &str) -> Option<Vec<String>> {
self.compiled().captures(text).map(|caps| {
caps.iter()
.skip(1)
.filter_map(|m| m.map(|m| m.as_str().to_string()))
.collect()
})
}
}
pub fn any_match(text: &str, patterns: &[Pattern]) -> bool {
patterns.iter().any(|p| p.matches(text))
}
pub fn last_n_lines(text: &str, n: usize) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines.len().saturating_sub(n);
lines[start..].join("\n")
}
pub fn best_match<'a>(text: &str, patterns: &'a [Pattern]) -> Option<&'a Pattern> {
patterns.iter().filter(|p| p.matches(text)).max_by(|a, b| {
a.confidence
.partial_cmp(&b.confidence)
.unwrap_or(std::cmp::Ordering::Equal)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pattern_matches() {
let p = Pattern::new("test", r"hello \w+", 0.9);
assert!(p.matches("hello world"));
assert!(!p.matches("goodbye world"));
}
#[test]
fn test_pattern_captures() {
let p = Pattern::new("test", r"hello (\w+)", 0.9);
let caps = p.captures("hello world").unwrap();
assert_eq!(caps, vec!["world"]);
}
#[test]
fn test_any_match() {
let patterns = [
Pattern::new("a", r"foo", 0.5),
Pattern::new("b", r"bar", 0.7),
];
assert!(any_match("there is a foo here", &patterns));
assert!(any_match("just bar", &patterns));
assert!(!any_match("nothing", &patterns));
}
#[test]
fn test_best_match_picks_highest_confidence() {
let patterns = [
Pattern::new("low", r"hello", 0.5),
Pattern::new("high", r"hello", 0.9),
Pattern::new("nomatch", r"goodbye", 1.0),
];
let best = best_match("hello there", &patterns).unwrap();
assert_eq!(best.name, "high");
}
}