diff --git a/src/common/swap.h b/src/common/swap.h index 32af0b6ac..466096f58 100644 --- a/src/common/swap.h +++ b/src/common/swap.h @@ -17,6 +17,8 @@ #pragma once +#include + #if defined(_MSC_VER) #include #elif defined(__linux__) @@ -605,6 +607,44 @@ struct swap_double_t { } }; +template +struct swap_enum_t { + static_assert(std::is_enum_v); + using base = std::underlying_type_t; + +public: + swap_enum_t() = default; + swap_enum_t(const T& v) : value(swap(v)) {} + + swap_enum_t& operator=(const T& v) { + value = swap(v); + return *this; + } + + operator T() const { + return swap(value); + } + + explicit operator base() const { + return static_cast(swap(value)); + } + +protected: + T value{}; + // clang-format off + using swap_t = std::conditional_t< + std::is_same_v, swap_16_t, std::conditional_t< + std::is_same_v, swap_16_t, std::conditional_t< + std::is_same_v, swap_32_t, std::conditional_t< + std::is_same_v, swap_32_t, std::conditional_t< + std::is_same_v, swap_64_t, std::conditional_t< + std::is_same_v, swap_64_t, void>>>>>>; + // clang-format on + static T swap(T x) { + return static_cast(swap_t::swap(static_cast(x))); + } +}; + #if COMMON_LITTLE_ENDIAN using u16_le = u16; using u32_le = u32; @@ -614,6 +654,9 @@ using s16_le = s16; using s32_le = s32; using s64_le = s64; +template +using enum_le = std::enable_if_t, T>; + using float_le = float; using double_le = double; @@ -626,6 +669,9 @@ using s32_be = swap_struct_t>; using u16_be = swap_struct_t>; using s16_be = swap_struct_t>; +template +using enum_be = swap_enum_t; + using float_be = swap_struct_t>; using double_be = swap_struct_t>; #else @@ -639,6 +685,9 @@ using s32_le = swap_struct_t>; using u16_le = swap_struct_t>; using s16_le = swap_struct_t>; +template +using enum_le = swap_enum_t; + using float_le = swap_struct_t>; using double_le = swap_struct_t>; @@ -650,6 +699,9 @@ using s16_be = s16; using s32_be = s32; using s64_be = s64; +template +using enum_be = std::enable_if_t, T>; + using float_be = float; using double_be = double;