-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: don't select hosts outside of filtered hosts
Signed-off-by: Nathanael DEMACON <[email protected]>
- Loading branch information
1 parent
22d9479
commit b0460e6
Showing
3 changed files
with
123 additions
and
29 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
type SearchableFn<T> = dyn FnMut(&&T, &str) -> bool; | ||
|
||
pub struct Searchable<T> | ||
where | ||
T: Clone, | ||
{ | ||
vec: Vec<T>, | ||
|
||
filter: Box<SearchableFn<T>>, | ||
filtered: Vec<T>, | ||
} | ||
|
||
impl<T> Searchable<T> | ||
where | ||
T: Clone, | ||
{ | ||
#[must_use] | ||
pub fn new<P>(vec: Vec<T>, search_value: &str, predicate: P) -> Self | ||
where | ||
P: FnMut(&&T, &str) -> bool + 'static, | ||
{ | ||
let mut searchable = Self { | ||
vec, | ||
|
||
filter: Box::new(predicate), | ||
filtered: Vec::new(), | ||
}; | ||
searchable.search(search_value); | ||
searchable | ||
} | ||
|
||
pub fn search(&mut self, value: &str) { | ||
if value.is_empty() { | ||
self.filtered = self.vec.clone(); | ||
return; | ||
} | ||
|
||
self.filtered = self | ||
.vec | ||
.iter() | ||
.filter(|host| (self.filter)(host, value)) | ||
.cloned() | ||
.collect(); | ||
} | ||
|
||
#[allow(clippy::must_use_candidate)] | ||
pub fn len(&self) -> usize { | ||
self.filtered.len() | ||
} | ||
|
||
#[allow(clippy::must_use_candidate)] | ||
pub fn is_empty(&self) -> bool { | ||
self.filtered.is_empty() | ||
} | ||
|
||
pub fn iter(&self) -> std::slice::Iter<T> { | ||
self.filtered.iter() | ||
} | ||
} | ||
|
||
impl<'a, T> IntoIterator for &'a Searchable<T> | ||
where | ||
T: Clone, | ||
{ | ||
type Item = &'a T; | ||
type IntoIter = std::slice::Iter<'a, T>; | ||
|
||
fn into_iter(self) -> Self::IntoIter { | ||
self.filtered.iter() | ||
} | ||
} | ||
|
||
impl<T> std::ops::Index<usize> for Searchable<T> | ||
where | ||
T: Clone, | ||
{ | ||
type Output = T; | ||
|
||
fn index(&self, index: usize) -> &Self::Output { | ||
&self.filtered[index] | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters