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"
13 #include "mozilla/Attributes.h"
20 * EnumSet<T> is a set of values defined by an enumeration. It is implemented
21 * using a 32 bit mask for each value so it will only work for enums with an int
22 * representation less than 32. It works both for enum and enum class types.
32 MOZ_IMPLICIT
EnumSet(T aEnum
)
33 : mBitField(bitFor(aEnum
))
36 EnumSet(T aEnum1
, T aEnum2
)
37 : mBitField(bitFor(aEnum1
) |
41 EnumSet(T aEnum1
, T aEnum2
, T aEnum3
)
42 : mBitField(bitFor(aEnum1
) |
47 EnumSet(T aEnum1
, T aEnum2
, T aEnum3
, T aEnum4
)
48 : mBitField(bitFor(aEnum1
) |
54 EnumSet(const EnumSet
& aEnumSet
)
55 : mBitField(aEnumSet
.mBitField
)
61 void operator+=(T aEnum
) {
62 mBitField
|= bitFor(aEnum
);
68 EnumSet
<T
> operator+(T aEnum
) const {
69 EnumSet
<T
> result(*this);
77 void operator+=(const EnumSet
<T
> aEnumSet
) {
78 mBitField
|= aEnumSet
.mBitField
;
84 EnumSet
<T
> operator+(const EnumSet
<T
> aEnumSet
) const {
85 EnumSet
<T
> result(*this);
93 void operator-=(T aEnum
) {
94 mBitField
&= ~(bitFor(aEnum
));
100 EnumSet
<T
> operator-(T aEnum
) const {
101 EnumSet
<T
> result(*this);
107 * Remove a set of elements
109 void operator-=(const EnumSet
<T
> aEnumSet
) {
110 mBitField
&= ~(aEnumSet
.mBitField
);
114 * Remove a set of elements
116 EnumSet
<T
> operator-(const EnumSet
<T
> aEnumSet
) const {
117 EnumSet
<T
> result(*this);
125 void operator&=(const EnumSet
<T
> aEnumSet
) {
126 mBitField
&= aEnumSet
.mBitField
;
132 EnumSet
<T
> operator&(const EnumSet
<T
> aEnumSet
) const {
133 EnumSet
<T
> result(*this);
142 bool operator==(const EnumSet
<T
> aEnumSet
) const {
143 return mBitField
== aEnumSet
.mBitField
;
147 * Test is an element is contained in the set
149 bool contains(T aEnum
) const {
150 return mBitField
& bitFor(aEnum
);
154 * Return the number of elements in the set
159 for (uint32_t bitField
= mBitField
; bitField
; bitField
>>= 1) {
166 bool isEmpty() const {
167 return mBitField
== 0;
170 uint32_t serialize() const {
174 void deserialize(uint32_t aValue
) {
179 static uint32_t bitFor(T aEnum
) {
180 uint32_t bitNumber
= (uint32_t)aEnum
;
181 MOZ_ASSERT(bitNumber
< 32);
182 return 1U << bitNumber
;
188 } // namespace mozilla
190 #endif /* mozilla_EnumSet_h_*/