use regex::Regex;
#[derive(Debug, Clone)]
pub struct Filter {
is_list_ignored: bool,
list: Vec<Regex>,
}
impl Filter {
#[inline]
pub(crate) fn new(ignore_matches: bool, list: Vec<Regex>) -> Self {
Self {
is_list_ignored: ignore_matches,
list,
}
}
#[inline]
pub(crate) fn should_keep(&self, entry: &str) -> bool {
if self.has_match(entry) {
!self.is_list_ignored
} else {
self.is_list_ignored
}
}
#[inline]
pub(crate) fn has_match(&self, value: &str) -> bool {
self.list.iter().any(|regex| regex.is_match(value))
}
#[inline]
pub(crate) fn ignore_matches(&self) -> bool {
self.is_list_ignored
}
#[inline]
pub(crate) fn optional_should_keep(filter: &Option<Self>, entry: &str) -> bool {
filter
.as_ref()
.map(|f| f.should_keep(entry))
.unwrap_or(true)
}
}
#[cfg(test)]
mod test {
use regex::Regex;
use super::*;
#[test]
fn filter_is_list_ignored() {
let results = [
"CPU socket temperature",
"wifi_0",
"motherboard temperature",
"amd gpu",
];
let ignore_true = Filter {
is_list_ignored: true,
list: vec![Regex::new("temperature").unwrap()],
};
assert_eq!(
results
.into_iter()
.filter(|r| ignore_true.should_keep(r))
.collect::<Vec<_>>(),
vec!["wifi_0", "amd gpu"]
);
let ignore_false = Filter {
is_list_ignored: false,
list: vec![Regex::new("temperature").unwrap()],
};
assert_eq!(
results
.into_iter()
.filter(|r| ignore_false.should_keep(r))
.collect::<Vec<_>>(),
vec!["CPU socket temperature", "motherboard temperature"]
);
let multi_true = Filter {
is_list_ignored: true,
list: vec![
Regex::new("socket").unwrap(),
Regex::new("temperature").unwrap(),
],
};
assert_eq!(
results
.into_iter()
.filter(|r| multi_true.should_keep(r))
.collect::<Vec<_>>(),
vec!["wifi_0", "amd gpu"]
);
let multi_false = Filter {
is_list_ignored: false,
list: vec![
Regex::new("socket").unwrap(),
Regex::new("temperature").unwrap(),
],
};
assert_eq!(
results
.into_iter()
.filter(|r| multi_false.should_keep(r))
.collect::<Vec<_>>(),
vec!["CPU socket temperature", "motherboard temperature"]
);
}
}