namespace Brutal.Enums; public static class EnumExtensions { /// /// All the methods here are only relevant for [Flags] enums /// (except for , which is only relevant for _non_-[Flags] enums). /// /// Terms: /// - A flag represents a single bit. /// - A mask represents a combination of bits (compound enum value). /// extension(ref T @this) where T : unmanaged, Enum { /// (Mask / bit-field / [Flags] enums only.) /// Add (set) the other flag/mask to this mask. [MethodImpl(MethodImplOptions.AggressiveInlining)] public T Add(T other) { @this |= other; return @this; } /// (Mask / bit-field / [Flags] enums only.) /// Remove (unset) the other flag/mask from this mask. [MethodImpl(MethodImplOptions.AggressiveInlining)] public T Remove(T other) { @this &= ~other; return @this; } /// (Mask / bit-field / [Flags] enums only.) /// Add/remove (set/unset) the other flag/mask to/from this mask. [MethodImpl(MethodImplOptions.AggressiveInlining)] public T Set(T other, bool enabled) { return enabled ? @this.Add(other) : @this.Remove(other); } } extension(T @this) where T : unmanaged, Enum { /// /// (Mask / bit-field / [Flags] enums only.) /// Does this mask entirely contain ? /// Ie, does this mask contain all the flags in ? ///
/// Similarly to , this method returns true if the set of bits /// represented by is empty, even if the current mask is empty. ///
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure] public bool ContainsAll(T other) { return (@this & other) == other; // same as @this.HasFlag(mask); } /// (Mask / bit-field / [Flags] enums only.) /// Does this mask contain any of the bits in ? [MethodImpl(MethodImplOptions.AggressiveInlining), Pure] public bool ContainsAny(T other) { return (@this & other) != default; } /// Return an containing this value. [MethodImpl(MethodImplOptions.AggressiveInlining), Pure] public EnumMask ToMask() => new(@this); } }