#[derive(Debug)]
pub struct FilterSet<T> {
filters: Option<Vec<Box<dyn Filter<T>>>>,
}
impl<T> FilterSet<T> {
pub fn add_filter<F: Filter<T> + 'static>(mut self, filter: F) -> Self {
if self.filters.is_none() {
self.filters = Some(Vec::new());
}
self.filters.as_mut().unwrap().push(Box::new(filter));
self
}
pub(crate) fn matches(&self, val: &T) -> bool {
if let Some(filters) = &self.filters {
for filter in filters.iter() {
if !filter.matches(&val) {
return false;
}
}
}
true
}
}
impl<T> Default for FilterSet<T> {
fn default() -> Self {
FilterSet { filters: None }
}
}
impl<T> Clone for FilterSet<T> {
fn clone(&self) -> Self {
Self {
filters: self.filters.clone(),
}
}
}
pub trait Filter<T>: std::fmt::Debug + dyn_clone::DynClone {
fn matches(&self, val: &T) -> bool;
}
impl<T> std::clone::Clone for Box<dyn Filter<T>> {
fn clone(&self) -> Self {
dyn_clone::clone_box(self.as_ref())
}
}
#[derive(Debug, Clone)]
pub enum FilterType {
StartsWith,
EndsWith,
Contains,
Equals
}