reorganize List from enum to struct; separate features to children mods

This commit is contained in:
postscriptum 2026-03-22 10:06:26 +02:00
parent 0b6b0ebd0e
commit e5268e49f1
2 changed files with 37 additions and 41 deletions

View file

@ -1,28 +1,13 @@
mod item;
use anyhow::Result; use anyhow::Result;
use item::Item;
use log::*; use log::*;
use std::collections::HashSet; use std::collections::HashSet;
use tokio::sync::RwLock; use tokio::sync::RwLock;
#[derive(PartialEq, Eq, Hash)] pub struct List {
pub enum Item { index: RwLock<HashSet<Item>>,
Ending(String),
Exact(String),
}
impl Item {
pub fn from_line(rule: &str) -> Self {
if let Some(item) = rule.strip_prefix(".") {
debug!("Add `{rule}` to the whitelist");
Self::Ending(item.to_string())
} else {
debug!("Add `{rule}` exact match to the whitelist");
Self::Exact(rule.to_string())
}
}
}
pub enum List {
Allow(RwLock<HashSet<Item>>),
} }
impl List { impl List {
@ -45,34 +30,26 @@ impl List {
} }
} }
info!("Total whitelist entries parsed: {}", this.len()); info!("Total whitelist entries parsed: {}", this.len());
Ok(Self::Allow(RwLock::new(this))) Ok(Self {
index: RwLock::new(this),
})
} }
pub async fn any(&self, values: &[&str]) -> bool { pub async fn any(&self, values: &[&str]) -> bool {
match self { let guard = self.index.read().await;
Self::Allow(list) => { values.iter().any(|&value| {
let guard = list.read().await; guard.iter().any(|item| match item {
values.iter().any(|&value| { Item::Exact(v) => v == value,
guard.iter().any(|item| match item { Item::Ending(v) => value.ends_with(v),
Item::Exact(v) => v == value, })
Item::Ending(v) => value.ends_with(v), })
})
})
}
}
} }
pub async fn entries(&self) -> u64 { pub async fn entries(&self) -> u64 {
match self { self.index.read().await.len() as u64
Self::Allow(list) => list.read().await.len() as u64,
}
} }
pub async fn allow(&self, rule: &str) -> bool { pub async fn allow(&self, rule: &str) -> bool {
match self { self.index.write().await.insert(Item::from_line(rule))
List::Allow(list) => list.write().await.insert(Item::from_line(rule)),
}
} }
pub async fn block(&self, rule: &str) -> bool { pub async fn block(&self, rule: &str) -> bool {
match self { self.index.write().await.remove(&Item::from_line(rule))
List::Allow(list) => list.write().await.remove(&Item::from_line(rule)),
}
} }
} }

19
src/list/item.rs Normal file
View file

@ -0,0 +1,19 @@
use log::debug;
#[derive(PartialEq, Eq, Hash)]
pub enum Item {
Ending(String),
Exact(String),
}
impl Item {
pub fn from_line(rule: &str) -> Self {
if let Some(item) = rule.strip_prefix(".") {
debug!("Add `{rule}` to the whitelist");
Self::Ending(item.to_string())
} else {
debug!("Add `{rule}` exact match to the whitelist");
Self::Exact(rule.to_string())
}
}
}