From b54b52908cc61d8f7c778844d90e59568b811a36 Mon Sep 17 00:00:00 2001 From: Tim Kuijsten Date: Thu, 18 Mar 2021 23:28:59 +0100 Subject: [PATCH] use compiler intrinsics for byte swapping This is simpler and more robust than platform specific functions/macros since we support fewer compilers than platforms. (based on chiapos PR #183 and #187) --- src/util.h | 37 +++++++++++++++---------------------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/src/util.h b/src/util.h index 46b60e5b..1d9ee66a 100644 --- a/src/util.h +++ b/src/util.h @@ -3,31 +3,24 @@ #include "vdf_new.h" -/* Platform-specific byte swap macros. */ -#if defined(_WIN32) +// compiler-specific byte swap macros +#if defined(_MSC_VER) + #include -#define bswap_16(x) _byteswap_ushort(x) -#define bswap_32(x) _byteswap_ulong(x) -#define bswap_64(x) _byteswap_uint64(x) -#elif defined(__APPLE__) - -#include - -#define bswap_16(x) OSSwapInt16(x) -#define bswap_32(x) OSSwapInt32(x) -#define bswap_64(x) OSSwapInt64(x) -#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) -# if defined(__OpenBSD__) -# include -# else -# include -# endif -#define bswap_16(x) bswap16(x) -#define bswap_32(x) bswap32(x) -#define bswap_64(x) bswap64(x) +// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/byteswap-uint64-byteswap-ulong-byteswap-ushort?view=msvc-160 +inline uint16_t bswap_16(uint16_t x) { return _byteswap_ushort(x); } +inline uint32_t bswap_32(uint32_t x) { return _byteswap_ulong(x); } +inline uint64_t bswap_64(uint64_t x) { return _byteswap_uint64(x); } + +#elif defined(__clang__) || defined(__GNUC__) + +inline uint16_t bswap_16(uint16_t x) { return __builtin_bswap16(x); } +inline uint32_t bswap_32(uint32_t x) { return __builtin_bswap32(x); } +inline uint64_t bswap_64(uint64_t x) { return __builtin_bswap64(x); } + #else -#include +#error "unknown compiler, don't know how to swap bytes" #endif