[clang][headers][endian.h] add some common extensions (#187565)

This PR adds two common extensions to `endian.h` found in some
implementations which we've encountered usages of in existing code (which
are allowable under POSIX), namely:

- double underscore versions of the byte order macros
- PDP endianness macros  

(note: we don't attempt to implement the actual conversion helpers for
PDP endianness, as LLVM doesn't support these targeting platforms with
this endianness, we just provide the macro so code checking against them
on other targets will compile)
This commit is contained in:
David Tenty 2026-03-19 23:13:38 -04:00 committed by GitHub
parent 19ced5ad82
commit caf079fbb2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 21 additions and 1 deletions

View File

@ -25,8 +25,23 @@
#define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__
#define BIG_ENDIAN __ORDER_BIG_ENDIAN__
#define PDP_ENDIAN __ORDER_PDP_ENDIAN__
#define BYTE_ORDER __BYTE_ORDER__
// Define some compatibility macros if they are not defined.
#ifndef __BYTE_ORDER
#define __BYTE_ORDER BYTE_ORDER
#endif
#ifndef __LITTLE_ENDIAN
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#endif
#ifndef __BIG_ENDIAN
#define __BIG_ENDIAN BIG_ENDIAN
#endif
#ifndef __PDP_ENDIAN
#define __PDP_ENDIAN PDP_ENDIAN
#endif
#if BYTE_ORDER == LITTLE_ENDIAN
#define htobe16(x) \
@ -48,7 +63,7 @@
#define le32toh(x) __CLANG_ENDIAN_CAST(static_cast, uint32_t, x)
#define le64toh(x) __CLANG_ENDIAN_CAST(static_cast, uint64_t, x)
#else
#elif BYTE_ORDER == BIG_ENDIAN
#define htobe16(x) __CLANG_ENDIAN_CAST(static_cast, uint16_t, x)
#define htobe32(x) __CLANG_ENDIAN_CAST(static_cast, uint32_t, x)
@ -69,6 +84,8 @@
#define le64toh(x) \
__builtin_bswap64(__CLANG_ENDIAN_CAST(static_cast, uint64_t, x))
#else
#error "Unsupported endianness"
#endif
#endif // __has_include_next
#endif // __CLANG_ENDIAN_H

View File

@ -6,6 +6,9 @@
#include <endian.h>
_Static_assert(__LITTLE_ENDIAN == __ORDER_LITTLE_ENDIAN__, "");
_Static_assert(__BIG_ENDIAN == __ORDER_BIG_ENDIAN__, "");
_Static_assert(__PDP_ENDIAN == __ORDER_PDP_ENDIAN__, "");
#if BYTE_ORDER == BIG_ENDIAN