forked from Return-To-The-Roots/libutil
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenumUtils.h
More file actions
81 lines (67 loc) · 2.72 KB
/
enumUtils.h
File metadata and controls
81 lines (67 loc) · 2.72 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright (C) 2005 - 2021 Settlers Freaks (sf-team at siedler25.org)
//
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <boost/config.hpp>
#include <type_traits>
template<typename Enum>
struct IsBitset : std::false_type
{};
template<typename Enum>
constexpr bool IsValidBitset_v = IsBitset<Enum>::value && std::is_unsigned<std::underlying_type_t<Enum>>::value;
template<typename Enum>
using require_validBitset = std::enable_if_t<IsValidBitset_v<Enum>>;
template<typename Enum, typename = require_validBitset<Enum>>
constexpr auto operator&(Enum lhs, Enum rhs) noexcept
{
using Int = std::underlying_type_t<Enum>;
return Enum(static_cast<Int>(lhs) & static_cast<Int>(rhs));
}
template<typename Enum, typename = require_validBitset<Enum>>
constexpr auto operator|(Enum lhs, Enum rhs) noexcept
{
using Int = std::underlying_type_t<Enum>;
return Enum(static_cast<Int>(lhs) | static_cast<Int>(rhs));
}
template<typename Enum, typename = require_validBitset<Enum>>
constexpr Enum& operator&=(Enum& lhs, Enum rhs) noexcept
{
return lhs = lhs & rhs;
}
template<typename Enum, typename = require_validBitset<Enum>>
constexpr Enum& operator|=(Enum& lhs, Enum rhs) noexcept
{
return lhs = lhs | rhs;
}
namespace bitset {
template<typename Enum, typename = require_validBitset<Enum>>
BOOST_ATTRIBUTE_NODISCARD constexpr Enum clear(const Enum val, const Enum flag)
{
using Int = std::underlying_type_t<Enum>;
return val & Enum(~static_cast<const Int>(flag));
}
template<typename Enum, typename = require_validBitset<Enum>>
BOOST_ATTRIBUTE_NODISCARD constexpr Enum set(const Enum val, const Enum flag, const bool state = true)
{
return state ? (val | flag) : clear(val, flag);
}
template<typename Enum, typename = require_validBitset<Enum>>
BOOST_ATTRIBUTE_NODISCARD constexpr Enum toggle(const Enum val, const Enum flag)
{
using Int = std::underlying_type_t<Enum>;
return Enum(static_cast<const Int>(val) ^ static_cast<const Int>(flag));
}
template<typename Enum, typename = require_validBitset<Enum>>
BOOST_ATTRIBUTE_NODISCARD constexpr bool isSet(const Enum val, const Enum flag)
{
return (val & flag) == flag;
}
} // namespace bitset
/// Makes a strongly typed enum usable as a bitset
#define MAKE_BITSET_STRONG(Type) \
template<> \
struct IsBitset<Type> : std::true_type \
{}; \
/* NOLINTNEXTLINE(bugprone-macro-parentheses) */ \
static_assert(std::is_unsigned<std::underlying_type_t<Type>>::value, \
#Type " must use unsigned type as the underlying type")