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
)
63 mBitField
|= bitFor(aEnum
);
69 EnumSet
<T
> operator+(T aEnum
) const
71 EnumSet
<T
> result(*this);
79 void operator+=(const EnumSet
<T
> aEnumSet
)
81 mBitField
|= aEnumSet
.mBitField
;
87 EnumSet
<T
> operator+(const EnumSet
<T
> aEnumSet
) const
89 EnumSet
<T
> result(*this);
97 void operator-=(T aEnum
)
99 mBitField
&= ~(bitFor(aEnum
));
105 EnumSet
<T
> operator-(T aEnum
) const
107 EnumSet
<T
> result(*this);
113 * Remove a set of elements
115 void operator-=(const EnumSet
<T
> aEnumSet
)
117 mBitField
&= ~(aEnumSet
.mBitField
);
121 * Remove a set of elements
123 EnumSet
<T
> operator-(const EnumSet
<T
> aEnumSet
) const
125 EnumSet
<T
> result(*this);
133 void operator&=(const EnumSet
<T
> aEnumSet
)
135 mBitField
&= aEnumSet
.mBitField
;
141 EnumSet
<T
> operator&(const EnumSet
<T
> aEnumSet
) const
143 EnumSet
<T
> result(*this);
151 bool operator==(const EnumSet
<T
> aEnumSet
) const
153 return mBitField
== aEnumSet
.mBitField
;
157 * Test is an element is contained in the set.
159 bool contains(T aEnum
) const
161 return mBitField
& bitFor(aEnum
);
165 * Return the number of elements in the set.
170 for (uint32_t bitField
= mBitField
; bitField
; bitField
>>= 1) {
180 return mBitField
== 0;
183 uint32_t serialize() const
188 void deserialize(uint32_t aValue
)
194 static uint32_t bitFor(T aEnum
)
196 uint32_t bitNumber
= (uint32_t)aEnum
;
197 MOZ_ASSERT(bitNumber
< 32);
198 return 1U << bitNumber
;
204 } // namespace mozilla
206 #endif /* mozilla_EnumSet_h_*/