Line data Source code
1 : // Copyright 2019 the V8 project authors. All rights reserved.
2 : // Use of this source code is governed by a BSD-style license that can be
3 : // found in the LICENSE file.
4 :
5 : #ifndef V8_BASE_ENUM_SET_H_
6 : #define V8_BASE_ENUM_SET_H_
7 :
8 : #include <type_traits>
9 :
10 : #include "src/base/logging.h"
11 :
12 : namespace v8 {
13 : namespace base {
14 :
15 : // A poor man's version of STL's bitset: A bit set of enums E (without explicit
16 : // values), fitting into an integral type T.
17 : template <class E, class T = int>
18 : class EnumSet {
19 : static_assert(std::is_enum<E>::value, "EnumSet can only be used with enums");
20 :
21 : public:
22 7518 : constexpr EnumSet() = default;
23 :
24 : EnumSet(std::initializer_list<E> init) {
25 292 : for (E e : init) Add(e);
26 : }
27 :
28 : bool empty() const { return bits_ == 0; }
29 8998904 : bool contains(E element) const { return (bits_ & Mask(element)) != 0; }
30 : bool contains_any(const EnumSet& set) const {
31 : return (bits_ & set.bits_) != 0;
32 : }
33 77315903 : void Add(E element) { bits_ |= Mask(element); }
34 : void Add(const EnumSet& set) { bits_ |= set.bits_; }
35 6705 : void Remove(E element) { bits_ &= ~Mask(element); }
36 : void Remove(const EnumSet& set) { bits_ &= ~set.bits_; }
37 : void RemoveAll() { bits_ = 0; }
38 : void Intersect(const EnumSet& set) { bits_ &= set.bits_; }
39 2469 : T ToIntegral() const { return bits_; }
40 : bool operator==(const EnumSet& set) const { return bits_ == set.bits_; }
41 : bool operator!=(const EnumSet& set) const { return bits_ != set.bits_; }
42 : EnumSet operator|(const EnumSet& set) const {
43 : return EnumSet(bits_ | set.bits_);
44 : }
45 : EnumSet operator&(const EnumSet& set) const {
46 48943385 : return EnumSet(bits_ & set.bits_);
47 : }
48 :
49 : static constexpr EnumSet FromIntegral(T bits) { return EnumSet{bits}; }
50 :
51 : private:
52 : explicit constexpr EnumSet(T bits) : bits_(bits) {}
53 :
54 : static T Mask(E element) {
55 : DCHECK_GT(sizeof(T) * 8, static_cast<int>(element));
56 77311739 : return T{1} << static_cast<typename std::underlying_type<E>::type>(element);
57 : }
58 :
59 : T bits_ = 0;
60 : };
61 :
62 : } // namespace base
63 : } // namespace v8
64 :
65 : #endif // V8_BASE_ENUM_SET_H_
|