ohmu
·
2026-10-15
1// This translation unit pretends to be compiled on a big endian host, so that the endianness
2// detection in `common/endian.h` can be exercised on a little endian machine.
3//
4// The selection is a preprocessor decision, so it can be pinned with `_Static_assert` instead of by
5// running anything -- which matters, because the alternative would be to observe a byte swap at run
6// time on hardware that really is little endian, and that cannot work.
7//
8// The case this guards: GCC does not define `__BIG_ENDIAN__` at all, it only documents
9// `__BYTE_ORDER__` and the `__ORDER_*_ENDIAN__` values. A header that tests `#if __BIG_ENDIAN__`
10// therefore evaluates it as 0 on s390x and silently picks the little endian branch, byte swapping
11// values that were already big endian. `__BIG_ENDIAN__` is undefined here for exactly that reason:
12// a header that only looks at its presence, or at its value, fails the assertions below.
13//
14// System headers are pulled in before the macros are faked so that they are not affected.
15
16#include <stdint.h>
17#include <stdio.h>
18
19#include "common/textModifier.h"
20
21// What a big endian compiler reports ...
22#undef __BYTE_ORDER__
23#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
24// ... and what GCC does not report on such a machine, even though it is one.
25#undef __BIG_ENDIAN__
26
27#include "common/endian.h"
28
29// On a big endian host the byte order of the machine and the byte order of the data agree, so
30// reading a big endian value is a no-op ...
31_Static_assert(FF_READ_BE((uint16_t) 0x1122) == (uint16_t) 0x1122, "FF_READ_BE must be the identity on a big endian host");
32_Static_assert(FF_READ_BE(0x11223344u) == 0x11223344u, "FF_READ_BE must be the identity on a big endian host");
33_Static_assert(FF_READ_BE((uint64_t) 0x1122334455667788ull) == (uint64_t) 0x1122334455667788ull, "FF_READ_BE must be the identity on a big endian host");
34
35// ... and reading a little endian one swaps.
36_Static_assert(FF_READ_LE((uint16_t) 0x1122) == (uint16_t) 0x2211, "FF_READ_LE must swap on a big endian host");
37_Static_assert(FF_READ_LE(0x11223344u) == 0x44332211u, "FF_READ_LE must swap on a big endian host");
38_Static_assert(FF_READ_LE((uint64_t) 0x1122334455667788ull) == (uint64_t) 0x8877665544332211ull, "FF_READ_LE must swap on a big endian host");
39
40int main(void) {
41 // Everything this test asserts is checked at compile time, so reaching this line is the result.
42 puts("\033[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET);
43 return 0;
44}