Sequoia
Loading...
Searching...
No Matches
Bitmask.hpp
Go to the documentation of this file.
1
2// Copyright Oliver J. Rosten 2022. //
3// Distributed under the GNU GENERAL PUBLIC LICENSE, Version 3.0. //
4// (See accompanying file LICENSE.md or copy at //
5// https://www.gnu.org/licenses/gpl-3.0.en.html) //
7
8#pragma once
9
14#include <type_traits>
15
16#ifdef EXPOSE_SEQUOIA_BITMASK
17#define NAMESPACE_SEQUOIA_AS_BITMASK inline namespace sequoia_bitmask
18#else
19#define NAMESPACE_SEQUOIA_AS_BITMASK namespace sequoia
20#endif
21
22NAMESPACE_SEQUOIA_AS_BITMASK
23{
24
53 template<class T>
54 requires std::is_enum_v<T>
55 struct as_bitmask : std::false_type
56 {};
57
58 template<class T>
59 requires std::is_enum_v<T>
60 using as_bitmask_t = typename as_bitmask<T>::type;
61
62 template<class T>
63 requires std::is_enum_v<T>
64 constexpr bool as_bitmask_v{as_bitmask<T>::value};
65
66 template<class T>
67 requires as_bitmask_v<T>
68 [[nodiscard]]
69 constexpr T operator|(T lhs, T rhs) noexcept
70 {
71 using underlying = std::underlying_type_t<T>;
72 return static_cast<T>(static_cast<underlying>(lhs) | static_cast<underlying>(rhs));
73 }
74
75 template<class T>
76 requires as_bitmask_v<T>
77 constexpr T& operator|=(T& lhs, T rhs) noexcept
78 {
79 lhs = lhs | rhs;
80 return lhs;
81 }
82
83 template<class T>
84 requires as_bitmask_v<T>
85 [[nodiscard]]
86 constexpr T operator&(T lhs, T rhs) noexcept
87 {
88 using underlying = std::underlying_type_t<T>;
89 return static_cast<T>(static_cast<underlying>(lhs) & static_cast<underlying>(rhs));
90 }
91
92 template<class T>
93 requires as_bitmask_v<T>
94 constexpr T& operator&=(T& lhs, T rhs) noexcept
95 {
96 lhs = lhs & rhs;
97 return lhs;
98 }
99
100 template<class T>
101 requires as_bitmask_v<T>
102 [[nodiscard]]
103 constexpr T operator^(T lhs, T rhs) noexcept
104 {
105 using underlying = std::underlying_type_t<T>;
106 return static_cast<T>(static_cast<underlying>(lhs) ^ static_cast<underlying>(rhs));
107 }
108
109 template<class T>
110 requires as_bitmask_v<T>
111 constexpr T& operator^=(T& lhs, T rhs) noexcept
112 {
113 lhs = lhs ^ rhs;
114 return lhs;
115 }
116
117 template<class T>
118 requires as_bitmask_v<T>
119 [[nodiscard]]
120 constexpr T operator~(T om)
121 {
122 using underlying = std::underlying_type_t<T>;
123 return static_cast<T>(~static_cast<underlying>(om));
124 }
125}