use glob::Pattern;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Advice {
Before,
After,
Around,
}
impl Advice {
pub fn parse(word: &str) -> Option<Self> {
match word {
"before" => Some(Advice::Before),
"after" => Some(Advice::After),
"around" => Some(Advice::Around),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Intercept {
pub pattern: Pattern,
pub advice: Advice,
pub handler: String,
}
#[derive(Debug, Clone, Default)]
pub struct Registry {
list: Vec<Intercept>,
}
impl Registry {
pub fn new() -> Self {
Self::default()
}
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
pub fn register(&mut self, pattern: &str, advice: Advice, handler: &str) -> Result<(), String> {
let pat =
Pattern::new(pattern).map_err(|e| format!("Bad intercept pattern `{pattern}': {e}"))?;
self.list.push(Intercept {
pattern: pat,
advice,
handler: handler.to_string(),
});
Ok(())
}
pub fn matching(&self, name: &str) -> Vec<&Intercept> {
self.list
.iter()
.filter(|i| i.pattern.matches(name))
.collect()
}
pub fn clear(&mut self) {
self.list.clear();
}
}