aboutsummaryrefslogtreecommitdiff
path: root/include/cru/base/Bitmask.h
blob: 9b6b89573eb4554a4a29d9b604371200e268c817 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#pragma once

#include <functional>

namespace cru {
template <typename Tag, typename TUnderlying = unsigned>
struct Bitmask final {
  using Underlying = TUnderlying;

  constexpr Bitmask() : value(0) {}
  constexpr explicit Bitmask(TUnderlying value) : value(value) {}

  static constexpr Bitmask FromOffset(int offset) {
    return Bitmask(static_cast<TUnderlying>(1u << offset));
  }

  constexpr bool Has(Bitmask rhs) const { return (value & rhs.value) != 0; }

  Bitmask operator|(Bitmask rhs) const { return Bitmask(value | rhs.value); }
  Bitmask operator&(Bitmask rhs) const { return Bitmask(value & rhs.value); }
  Bitmask operator^(Bitmask rhs) const { return Bitmask(value ^ rhs.value); }
  Bitmask operator~() const { return Bitmask(~value); }
  Bitmask& operator|=(Bitmask rhs) {
    value |= rhs.value;
    return *this;
  }
  Bitmask& operator&=(Bitmask rhs) {
    value &= rhs.value;
    return *this;
  }
  Bitmask& operator^=(Bitmask rhs) {
    value ^= rhs.value;
    return *this;
  }

  bool operator==(Bitmask rhs) const { return this->value == rhs.value; }
  bool operator!=(Bitmask rhs) const { return this->value != rhs.value; }

  explicit operator TUnderlying() const { return value; }
  operator bool() const { return value != 0; }

  TUnderlying value;
};
}  // namespace cru

namespace std {
template <typename Tag, typename TUnderlying>
struct hash<cru::Bitmask<Tag, TUnderlying>> {
  using Bitmask = cru::Bitmask<Tag, TUnderlying>;

  std::size_t operator()(Bitmask bitmask) const {
    return std::hash<TUnderlying>{}(bitmask.value);
  }
};
}  // namespace std