diff --git a/src/internal.rs b/src/internal.rs index fd09a1a3..78120b1b 100644 --- a/src/internal.rs +++ b/src/internal.rs @@ -307,6 +307,20 @@ macro_rules! __impl_internal_bitflags { } } + #[inline] + pub fn insert_if(&mut self, other: Self, value: bool) { + if value { + self.insert(other); + } + } + + #[inline] + pub fn remove_if(&mut self, other: Self, value: bool) { + if value { + self.remove(other); + } + } + #[inline] #[must_use] pub const fn intersection(self, other: Self) -> Self { diff --git a/src/lib.rs b/src/lib.rs index 8c8fab7c..bbdce79c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1085,6 +1085,24 @@ mod tests { assert_eq!(e1, Flags::A | Flags::B); } + #[test] + fn test_insert_if() { + let mut e1 = Flags::A; + e1.insert_if(Flags::B, true); + e1.insert_if(Flags::C, false); + + assert_eq!(e1, Flags::A | Flags::B); + } + + #[test] + fn test_remove_if() { + let mut e1 = Flags::A | Flags::B | Flags::C; + e1.remove_if(Flags::A, true); + e1.remove_if(Flags::B, false); + + assert_eq!(e1, Flags::B | Flags::C); + } + #[test] fn test_assignment_operators() { let mut m1 = Flags::empty(); diff --git a/src/public.rs b/src/public.rs index 3f11ea60..a7c32151 100644 --- a/src/public.rs +++ b/src/public.rs @@ -167,6 +167,18 @@ macro_rules! __impl_public_bitflags { self.0.set(other.0, value) } + /// Inserts the specified flags if the passed value is true. + #[inline] + pub fn insert_if(&mut self, other: Self, value: bool) { + self.0.insert_if(other.0, value) + } + + /// Removes the specified flags if the passed value is true. + #[inline] + pub fn remove_if(&mut self, other: Self, value: bool) { + self.0.remove_if(other.0, value) + } + /// Returns the intersection between the flags in `self` and /// `other`. /// @@ -439,6 +451,14 @@ macro_rules! __impl_public_bitflags { fn set(&mut self, other: $PublicBitFlags, value: bool) { $PublicBitFlags::set(self, other, value) } + + fn insert_if(&mut self, other: $PublicBitFlags, value: bool) { + $PublicBitFlags::insert_if(self, other, value) + } + + fn remove_if(&mut self, other: $PublicBitFlags, value: bool) { + $PublicBitFlags::remove_if(self, other, value) + } } impl $crate::__private::ImplementedByBitFlagsMacro for $PublicBitFlags {} diff --git a/src/traits.rs b/src/traits.rs index ce4921bf..135669c8 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -70,6 +70,12 @@ pub trait BitFlags: ImplementedByBitFlagsMacro { /// Inserts or removes the specified flags depending on the passed value. fn set(&mut self, other: Self, value: bool); + + /// Inserts the specified flags if the value is true; does nothing if the value is false. + fn insert_if(&mut self, other: Self, value: bool); + + /// Removes the specified flags if the value is true; does nothing if the value is false. + fn remove_if(&mut self, other: Self, value: bool); } /// A marker trait that signals that an implementation of `BitFlags` came from the `bitflags!` macro.