add bitfields swap and hash

This commit is contained in:
BlackMATov
2020-12-18 21:35:42 +07:00
parent 4e1d8b5644
commit 55055a23dc
2 changed files with 46 additions and 0 deletions

View File

@@ -6,7 +6,9 @@
#pragma once
#include <functional>
#include <type_traits>
#include <utility>
namespace enum_hpp::bitflags
{
@@ -21,6 +23,11 @@ namespace enum_hpp::bitflags
bitflags(const bitflags&) = default;
bitflags& operator=(const bitflags&) = default;
constexpr void swap(bitflags& other) noexcept {
using std::swap;
swap(flags_, other.flags_);
}
constexpr bitflags(enum_type flags)
: flags_(static_cast<underlying_type>(flags)) {}
@@ -60,6 +67,21 @@ namespace enum_hpp::bitflags
private:
underlying_type flags_{};
};
template < typename Enum >
constexpr void swap(bitflags<Enum>& l, bitflags<Enum>& r) noexcept {
l.swap(r);
}
}
namespace std
{
template < typename Enum >
struct hash<enum_hpp::bitflags::bitflags<Enum>> {
size_t operator()(enum_hpp::bitflags::bitflags<Enum> bf) const noexcept {
return hash<Enum>{}(bf.as_enum());
}
};
}
namespace enum_hpp::bitflags

View File

@@ -60,6 +60,30 @@ TEST_CASE("enum_bitflags") {
}
}
SUBCASE("swap") {
{
bf::bitflags f = access::read | access::write;
bf::bitflags g = access::write | access::execute;
f.swap(g);
CHECK(f == (access::write | access::execute));
CHECK(g == (access::read | access::write));
}
{
bf::bitflags f = access::read | access::write;
bf::bitflags g = access::write | access::execute;
swap(f, g);
CHECK(f == (access::write | access::execute));
CHECK(g == (access::read | access::write));
}
}
SUBCASE("hash") {
std::hash<bf::bitflags<access>> hasher1;
std::hash<bf::bitflags<access>> hasher2;
CHECK(hasher1(access::read) == hasher2(access::read));
CHECK(hasher1(access::read) != hasher2(access::read_write));
}
SUBCASE("enum_operators") {
STATIC_CHECK((~access::read) == bf::bitflags<access>(0xFE));
STATIC_CHECK((access::read | access::write) == bf::bitflags<access>(0x3));