From 55055a23dc476f6eed03c81f46ef8e109782cf6e Mon Sep 17 00:00:00 2001 From: BlackMATov Date: Fri, 18 Dec 2020 21:35:42 +0700 Subject: [PATCH] add bitfields swap and hash --- headers/enum.hpp/enum_bitflags.hpp | 22 ++++++++++++++++++++++ untests/enum_bitflags_tests.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/headers/enum.hpp/enum_bitflags.hpp b/headers/enum.hpp/enum_bitflags.hpp index df2ac34..4d69b17 100644 --- a/headers/enum.hpp/enum_bitflags.hpp +++ b/headers/enum.hpp/enum_bitflags.hpp @@ -6,7 +6,9 @@ #pragma once +#include #include +#include 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(flags)) {} @@ -60,6 +67,21 @@ namespace enum_hpp::bitflags private: underlying_type flags_{}; }; + + template < typename Enum > + constexpr void swap(bitflags& l, bitflags& r) noexcept { + l.swap(r); + } +} + +namespace std +{ + template < typename Enum > + struct hash> { + size_t operator()(enum_hpp::bitflags::bitflags bf) const noexcept { + return hash{}(bf.as_enum()); + } + }; } namespace enum_hpp::bitflags diff --git a/untests/enum_bitflags_tests.cpp b/untests/enum_bitflags_tests.cpp index ab96d14..0316a9f 100644 --- a/untests/enum_bitflags_tests.cpp +++ b/untests/enum_bitflags_tests.cpp @@ -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> hasher1; + std::hash> 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(0xFE)); STATIC_CHECK((access::read | access::write) == bf::bitflags(0x3));