Skip to content

Commit 4f88005

Browse files
Add bitset utility functions
Implement utility functions to set, clear, toggle, and query a bitset for more concise code.
1 parent 82e2584 commit 4f88005

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

libs/common/include/s25util/enumUtils.h

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
#pragma once
66

7+
#include <boost/config.hpp>
78
#include <type_traits>
89

910
template<typename Enum>
@@ -42,6 +43,34 @@ constexpr auto operator|=(Enum& lhs, Enum rhs) noexcept
4243
return lhs = lhs | rhs;
4344
}
4445

46+
namespace bitset {
47+
template<typename Enum, typename = require_validBitset<Enum>>
48+
BOOST_ATTRIBUTE_NODISCARD constexpr Enum clear(const Enum val, const Enum flag)
49+
{
50+
using Int = std::underlying_type_t<Enum>;
51+
return val & Enum(~static_cast<const Int>(flag));
52+
}
53+
54+
template<typename Enum, typename = require_validBitset<Enum>>
55+
BOOST_ATTRIBUTE_NODISCARD constexpr Enum set(const Enum val, const Enum flag, const bool state = true)
56+
{
57+
return state ? (val | flag) : clear(val, flag);
58+
}
59+
60+
template<typename Enum, typename = require_validBitset<Enum>>
61+
BOOST_ATTRIBUTE_NODISCARD constexpr Enum toggle(const Enum val, const Enum flag)
62+
{
63+
using Int = std::underlying_type_t<Enum>;
64+
return Enum(static_cast<const Int>(val) ^ static_cast<const Int>(flag));
65+
}
66+
67+
template<typename Enum, typename = require_validBitset<Enum>>
68+
BOOST_ATTRIBUTE_NODISCARD constexpr bool isSet(const Enum val, const Enum flag)
69+
{
70+
return (val & flag) == flag;
71+
}
72+
} // namespace bitset
73+
4574
/// Makes a strongly typed enum usable as a bitset
4675
#define MAKE_BITSET_STRONG(Type) \
4776
template<> \

0 commit comments

Comments
 (0)