Skip to content

Commit

Permalink
use compiler intrinsics for byte swapping
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
timkuijsten committed Apr 12, 2021
1 parent b23db7d commit b54b529
Showing 1 changed file with 15 additions and 22 deletions.
37 changes: 15 additions & 22 deletions src/util.h
Expand Up @@ -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 <cstdlib>

#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 <libkern/OSByteOrder.h>

#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 <machine/endian.h>
# else
# include <sys/endian.h>
# 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 <byteswap.h>
#error "unknown compiler, don't know how to swap bytes"
#endif


Expand Down

0 comments on commit b54b529

Please sign in to comment.