diff options
author | crupest <crupest@outlook.com> | 2024-10-06 13:57:39 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2024-10-06 13:57:39 +0800 |
commit | dfe62dcf8bcefc523b466e127c3edc4dc2756629 (patch) | |
tree | 1c751a14ba0da07ca2ff805633f97568060aa4c9 /include/cru/base/Bitmask.h | |
parent | f51eb955e188858272230a990565931e7403f23b (diff) | |
download | cru-dfe62dcf8bcefc523b466e127c3edc4dc2756629.tar.gz cru-dfe62dcf8bcefc523b466e127c3edc4dc2756629.tar.bz2 cru-dfe62dcf8bcefc523b466e127c3edc4dc2756629.zip |
Rename common to base.
Diffstat (limited to 'include/cru/base/Bitmask.h')
-rw-r--r-- | include/cru/base/Bitmask.h | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/include/cru/base/Bitmask.h b/include/cru/base/Bitmask.h new file mode 100644 index 00000000..9b6b8957 --- /dev/null +++ b/include/cru/base/Bitmask.h @@ -0,0 +1,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 |