filterable-enum 0.2.0

A library for generating filterable enums (Combining bitflags and discriminated unions)
Documentation
#![warn(clippy::all, clippy::nursery)]
#![doc = include_str!("../README.md")]

extern crate self as filterable_enum;

pub use enumflags2;

pub use filterable_enum_derive::filterable_enum;

/// An enum that can be filtered by its variant's bitflag.
///
/// Implemented by [`macro@filterable_enum`] directly on the annotated enum.
pub trait FilterableEnum: Sized {
    type Id;
    type Filter: EnumFilter<Self::Id>;

    /// Reads the bitflag identifying the current variant.
    fn filterable_id(&self) -> Self::Id;

    /// Borrows this enum if its variant is included in `filter`.
    fn filter_ref(&self, filter: impl Into<Self::Filter>) -> Option<&Self> {
        if filter.into().contains(self.filterable_id()) {
            Some(self)
        } else {
            None
        }
    }

    /// Takes this enum if its variant is included in `filter`.
    fn filter_and_take(self, filter: impl Into<Self::Filter>) -> Option<Self> {
        if filter.into().contains(self.filterable_id()) {
            Some(self)
        } else {
            None
        }
    }
}

/// A filter that tests whether it includes a variant's bitflag.
pub trait EnumFilter<Id> {
    fn contains(&self, id: Id) -> bool;
}

impl<Id: enumflags2::BitFlag> EnumFilter<Id> for enumflags2::BitFlags<Id> {
    fn contains(&self, id: Id) -> bool {
        self.intersects(id)
    }
}