1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* A set abstraction for enumeration values. */
9 #ifndef mozilla_EnumSet_h
10 #define mozilla_EnumSet_h
12 #include "mozilla/Assertions.h"
19 * EnumSet<T> is a set of values defined by an enumeration. It is implemented
20 * using a 32 bit mask for each value so it will only work for enums with an int
21 * representation less than 32. It works both for enum and enum class types.
35 EnumSet(T aEnum1
, T aEnum2
)
36 : mBitField(bitFor(aEnum1
) |
40 EnumSet(T aEnum1
, T aEnum2
, T aEnum3
)
41 : mBitField(bitFor(aEnum1
) |
46 EnumSet(T aEnum1
, T aEnum2
, T aEnum3
, T aEnum4
)
47 : mBitField(bitFor(aEnum1
) |
53 EnumSet(const EnumSet
& aEnumSet
)
54 : mBitField(aEnumSet
.mBitField
)
60 void operator+=(T aEnum
) {
61 mBitField
|= bitFor(aEnum
);
67 EnumSet
<T
> operator+(T aEnum
) const {
68 EnumSet
<T
> result(*this);
76 void operator+=(const EnumSet
<T
> aEnumSet
) {
77 mBitField
|= aEnumSet
.mBitField
;
83 EnumSet
<T
> operator+(const EnumSet
<T
> aEnumSet
) const {
84 EnumSet
<T
> result(*this);
92 void operator-=(T aEnum
) {
93 mBitField
&= ~(bitFor(aEnum
));
99 EnumSet
<T
> operator-(T aEnum
) const {
100 EnumSet
<T
> result(*this);
106 * Remove a set of elements
108 void operator-=(const EnumSet
<T
> aEnumSet
) {
109 mBitField
&= ~(aEnumSet
.mBitField
);
113 * Remove a set of elements
115 EnumSet
<T
> operator-(const EnumSet
<T
> aEnumSet
) const {
116 EnumSet
<T
> result(*this);
124 void operator&=(const EnumSet
<T
> aEnumSet
) {
125 mBitField
&= aEnumSet
.mBitField
;
131 EnumSet
<T
> operator&(const EnumSet
<T
> aEnumSet
) const {
132 EnumSet
<T
> result(*this);
141 bool operator==(const EnumSet
<T
> aEnumSet
) const {
142 return mBitField
== aEnumSet
.mBitField
;
146 * Test is an element is contained in the set
148 bool contains(T aEnum
) const {
149 return mBitField
& bitFor(aEnum
);
153 * Return the number of elements in the set
158 for (uint32_t bitField
= mBitField
; bitField
; bitField
>>= 1) {
166 static uint32_t bitFor(T aEnum
) {
167 uint32_t bitNumber(aEnum
);
168 MOZ_ASSERT(bitNumber
< 32);
169 return 1U << bitNumber
;
175 } // namespace mozilla
177 #endif /* mozilla_EnumSet_h_*/