Skip to content

Commit

Permalink
chore!: improve ip filter constructor and methods
Browse files Browse the repository at this point in the history
  • Loading branch information
cavivie committed Apr 10, 2024
1 parent 0d98fb8 commit 93897c9
Showing 1 changed file with 23 additions and 22 deletions.
45 changes: 23 additions & 22 deletions src/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,31 @@ pub struct IpFilters<'a> {

impl<'a> Default for IpFilters<'a> {
fn default() -> Self {
Self::new(vec![])
Self::new()
}
}

impl<'a> IpFilters<'a> {
pub fn new(filters: Vec<IpFilter<'a>>) -> Self {
Self { filters }
pub fn new() -> Self {
Self {
filters: Default::default(),
}
}

pub fn with_non_broadcast() -> Self {
Self::new(vec![Box::new(|src, dst| {
macro_rules! non_broadcast {
($addr:expr) => {
match $addr {
IpAddr::V4(v4) => {
!(v4.is_broadcast() || v4.is_multicast() || v4.is_multicast())
}
IpAddr::V6(v6) => !(v6.is_multicast() || v6.is_unspecified()),
}
};
}
non_broadcast!(src) && non_broadcast!(dst)
})])
macro_rules! non_broadcast {
($addr:ident) => {
match $addr {
IpAddr::V4(a) => !(a.is_broadcast() || a.is_multicast() || a.is_multicast()),
IpAddr::V6(a) => !(a.is_multicast() || a.is_unspecified()),
}
};
}
Self {
filters: vec![Box::new(|src, dst| {
non_broadcast!(src) && non_broadcast!(dst)
})],
}
}

pub fn add(&mut self, filter: IpFilter<'a>) {
Expand All @@ -44,12 +46,11 @@ impl<'a> IpFilters<'a> {
self.filters.push(Box::new(filter));
}

pub fn add_all<I: IntoIterator<Item = IpFilter<'a>>>(&mut self, filters: I) {
self.filters.extend(filters.into_iter());
}

pub fn is_allowed(&self, src: &IpAddr, dst: &IpAddr) -> bool {
for filter in &self.filters {
if !filter(src, dst) {
return false;
}
}
true
self.filters.iter().all(|filter| filter(src, dst))
}
}

0 comments on commit 93897c9

Please sign in to comment.