Skip to main content

filterable_enum/
lib.rs

1#![warn(clippy::all, clippy::nursery)]
2#![doc = include_str!("../README.md")]
3
4extern crate self as filterable_enum;
5
6pub use enumflags2;
7
8pub use filterable_enum_derive::filterable_enum;
9
10/// An enum that can be filtered by its variant's bitflag.
11///
12/// Implemented by [`macro@filterable_enum`] directly on the annotated enum.
13pub trait FilterableEnum: Sized {
14    type Id;
15    type Filter: EnumFilter<Self::Id>;
16
17    /// Reads the bitflag identifying the current variant.
18    fn filterable_id(&self) -> Self::Id;
19
20    /// Borrows this enum if its variant is included in `filter`.
21    fn filter_ref(&self, filter: impl Into<Self::Filter>) -> Option<&Self> {
22        if filter.into().contains(self.filterable_id()) {
23            Some(self)
24        } else {
25            None
26        }
27    }
28
29    /// Takes this enum if its variant is included in `filter`.
30    fn filter_and_take(self, filter: impl Into<Self::Filter>) -> Option<Self> {
31        if filter.into().contains(self.filterable_id()) {
32            Some(self)
33        } else {
34            None
35        }
36    }
37}
38
39/// A filter that tests whether it includes a variant's bitflag.
40pub trait EnumFilter<Id> {
41    fn contains(&self, id: Id) -> bool;
42}
43
44impl<Id: enumflags2::BitFlag> EnumFilter<Id> for enumflags2::BitFlags<Id> {
45    fn contains(&self, id: Id) -> bool {
46        self.intersects(id)
47    }
48}