fix: just use compiler builtins with endianess

this is the most portable and clean approach. Compiler built-ins should
always be present regardless, and is more maintainable, since we're not
trying to keep up with various versions of this header.
This commit is contained in:
2025-09-13 19:38:38 +02:00
parent c2e1b67b4c
commit d9ddae770a

View File

@@ -1,46 +1,9 @@
/* Copyright (c) 2025 Quinn
* Licensed under the MIT Licence. See LICENSE for details */
#ifndef PORTABLE_ENDIAN_H
#define PORTABLE_ENDIAN_H 1
#if defined(__GNUC__)
/* test for the byteswap header */
#if __has_include(<byteswap.h>)
#include <byteswap.h>
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define le16toh(x) (x)
#define le32toh(x) (x)
#define le64toh(x) (x)
#define htole16(x) (x)
#define htole32(x) (x)
#define htole64(x) (x)
#define be16toh(x) bswap_16(x)
#define be32toh(x) bswap_32(x)
#define be64toh(x) bswap_64(x)
#define htobe16(x) bswap_16(x)
#define htobe32(x) bswap_32(x)
#define htobe64(x) bswap_64(x)
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define le16toh(x) bswap_16(x)
#define le32toh(x) bswap_32(x)
#define le64toh(x) bswap_64(x)
#define htole16(x) bswap_16(x)
#define htole32(x) bswap_32(x)
#define htole64(x) bswap_64(x)
#define be16toh(x) (x)
#define be32toh(x) (x)
#define be64toh(x) (x)
#define htobe16(x) (x)
#define htobe32(x) (x)
#define htobe64(x) (x)
#else
#error machine architecture unsupported! Expected either big-endian or little-endian, make sure to use a compiler which defines __BYTE_ORDER__ (like clang or gcc)
#endif /* byte order */
/* otherwise, utilise the compiler built-ins */
#else
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define le16toh(x) __uint16_identity(x)
#define le32toh(x) __uint32_identity(x)
@@ -71,10 +34,7 @@
#error machine architecture unsupported! Expected either big-endian or little-endian, make sure to use a compiler which defines __BYTE_ORDER__ (like clang or gcc)
#endif /* byte order */
#endif /* has byteswap.h */
#else
#error GNU C is unavailable
#endif /* __GNUC__ */
#endif /* PORTABLE_ENDIAN_H */