AK: Make BigEndian<> and LittleEndian<> work with enum classes

This commit is contained in:
Nico Weber 2022-12-28 12:57:37 -05:00 committed by Sam Atkins
parent a21703f1df
commit 57126a0d3c
Notes: sideshowbarker 2024-07-17 02:30:01 +09:00
2 changed files with 18 additions and 6 deletions

View file

@ -43,11 +43,11 @@ ALWAYS_INLINE constexpr T convert_between_host_and_little_endian(T value)
return value;
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
if constexpr (sizeof(T) == 8)
return __builtin_bswap64(value);
return static_cast<T>(__builtin_bswap64(static_cast<u64>(value)));
if constexpr (sizeof(T) == 4)
return __builtin_bswap32(value);
return static_cast<T>(__builtin_bswap32(static_cast<u32>(value)));
if constexpr (sizeof(T) == 2)
return __builtin_bswap16(value);
return static_cast<T>(__builtin_bswap16(static_cast<u16>(value)));
if constexpr (sizeof(T) == 1)
return value;
#endif
@ -58,11 +58,11 @@ ALWAYS_INLINE constexpr T convert_between_host_and_big_endian(T value)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
if constexpr (sizeof(T) == 8)
return __builtin_bswap64(value);
return static_cast<T>(__builtin_bswap64(static_cast<u64>(value)));
if constexpr (sizeof(T) == 4)
return __builtin_bswap32(value);
return static_cast<T>(__builtin_bswap32(static_cast<u32>(value)));
if constexpr (sizeof(T) == 2)
return __builtin_bswap16(value);
return static_cast<T>(__builtin_bswap16(static_cast<u16>(value)));
if constexpr (sizeof(T) == 1)
return value;
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__

View file

@ -15,3 +15,15 @@ static_assert(BigEndian<u32> { 42 } == 42, "Big endian values should be value co
static_assert(LittleEndian<u32> {} == 0, "Little endian values should be default constructed in a constexpr context.");
static_assert(LittleEndian<u32> { 42 } == 42, "Little endian values should be value constructed in a constexpr context.");
enum class Enum8 : u8 { Element = 1 };
static_assert(BigEndian<Enum8> { Enum8::Element } == Enum8::Element);
enum class Enum16 : u16 { Element = 2 };
static_assert(BigEndian<Enum16> { Enum16::Element } == Enum16::Element);
enum class Enum32 : u32 { Element = 3 };
static_assert(BigEndian<Enum32> { Enum32::Element } == Enum32::Element);
enum class Enum64 : u64 { Element = 4 };
static_assert(BigEndian<Enum64> { Enum64::Element } == Enum64::Element);