Added bitFlagsToInt() and bitFlagsFromInt() methods for converting bit flags to and from integer types.
This commit is contained in:
parent
ede7477ffa
commit
cd66b76a8f
@ -5,8 +5,11 @@
|
|||||||
#define MIJIN_UTIL_BITFLAGS_HPP_INCLUDED 1
|
#define MIJIN_UTIL_BITFLAGS_HPP_INCLUDED 1
|
||||||
|
|
||||||
#include <bit>
|
#include <bit>
|
||||||
|
#include <compare>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
|
|
||||||
|
#include "../util/traits.hpp"
|
||||||
|
|
||||||
namespace mijin
|
namespace mijin
|
||||||
{
|
{
|
||||||
|
|
||||||
@ -90,10 +93,40 @@ private:
|
|||||||
template<typename T>
|
template<typename T>
|
||||||
constexpr bool is_bitflags_v = std::is_base_of_v<BitFlags<T>, T>;
|
constexpr bool is_bitflags_v = std::is_base_of_v<BitFlags<T>, T>;
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
concept BitFlagsType = is_bitflags_v<T>;
|
||||||
|
|
||||||
//
|
//
|
||||||
// public functions
|
// public functions
|
||||||
//
|
//
|
||||||
|
|
||||||
|
template<std::integral TInt, BitFlagsType T>
|
||||||
|
TInt bitFlagsToInt(const BitFlags<T>& flags) noexcept
|
||||||
|
{
|
||||||
|
static constexpr std::size_t BYTES = std::min(sizeof(T), sizeof(TInt));
|
||||||
|
TInt result = 0;
|
||||||
|
|
||||||
|
for (std::size_t off = 0; off < BYTES; ++off)
|
||||||
|
{
|
||||||
|
result |= static_cast<TInt>(*(std::bit_cast<const std::byte*>(&flags) + off)) << (off * 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<BitFlagsType T, std::integral TInt>
|
||||||
|
T bitFlagsFromInt(TInt intVal) noexcept
|
||||||
|
{
|
||||||
|
static constexpr std::size_t BYTES = std::min(sizeof(T), sizeof(TInt));
|
||||||
|
T result = {};
|
||||||
|
|
||||||
|
for (std::size_t off = 0; off < BYTES; ++off)
|
||||||
|
{
|
||||||
|
(*(std::bit_cast<std::byte*>(&result) + off)) = static_cast<std::byte>(intVal >> (off * 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
} // namespace mijin
|
} // namespace mijin
|
||||||
|
|
||||||
#endif // !defined(MIJIN_UTIL_BITFLAGS_HPP_INCLUDED)
|
#endif // !defined(MIJIN_UTIL_BITFLAGS_HPP_INCLUDED)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user