FeatherMC/src/util/ByteUtil.h

39 lines
1.2 KiB
C++

#pragma once
#ifdef _MSC_VER
#include <stdlib.h>
#endif
enum class Endian
{
Little,
Big
};
// Reverses the byte order of a primitive value of any typical size
template <typename T>
inline constexpr T ReverseBytes(T n)
{
// 1 byte, cannot reverse
if constexpr (sizeof(T) == 1) return n;
#ifdef __GNUC__
// GCC intrinsic byte swaps
// https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-_005f_005fbuiltin_005fbswap16
if constexpr (sizeof(T) == 2) return __builtin_bswap16(n); // 2 bytes
else if constexpr (sizeof(T) == 4) return __builtin_bswap32(n); // 4 bytes
else if constexpr (sizeof(T) == 8) return __builtin_bswap64(n); // 8 bytes
#elif defined(_MSC_VER)
// MSVC intrinsic byteswaps
// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/byteswap-uint64-byteswap-ulong-byteswap-ushort
if constexpr (sizeof(T) == 2) return _byteswap_ushort(n); // 2 bytes
else if constexpr (sizeof(T) == 4) return _byteswap_ulong(n); // 4 bytes
else if constexpr (sizeof(T) == 8) return _byteswap_uint64(n); // 8 bytes
#endif
//else static_assert(false, "Attempted to call ReverseBytes() on type with unusual size.");
}