Skip to content

Commit

Permalink
Move endianness check to compile time if it possible
Browse files Browse the repository at this point in the history
  • Loading branch information
phprus committed Jan 4, 2022
1 parent 074cc78 commit 3f6e0f1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
2 changes: 1 addition & 1 deletion include/fmt/chrono.h
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ inline void write_digit2_separated(char* buf, unsigned a, unsigned b,
auto usep = static_cast<unsigned long long>(sep);
// Add ASCII '0' to each digit byte and insert separators.
digits |= 0x3030003030003030 | (usep << 16) | (usep << 40);
if (is_big_endian()) {
if (const_check(is_big_endian())) {
char tmp[8];
memcpy(tmp, &digits, 8);
std::reverse_copy(tmp, tmp + 8, buf);
Expand Down
12 changes: 11 additions & 1 deletion include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -295,12 +295,22 @@ FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To {
return to;
}

#ifdef _WIN32
constexpr auto is_big_endian() -> bool { return false; }
#elif defined(__BIG_ENDIAN__)
constexpr auto is_big_endian() -> bool { return true; }
#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)
constexpr auto is_big_endian() -> bool {
return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__;
}
#else
inline auto is_big_endian() -> bool {
struct bytes {
char data[sizeof(int)];
};
return bit_cast<bytes>(1).data[0] == 0;
}
#endif

// A fallback implementation of uintptr_t for systems that lack it.
struct fallback_uintptr {
Expand All @@ -309,7 +319,7 @@ struct fallback_uintptr {
fallback_uintptr() = default;
explicit fallback_uintptr(const void* p) {
*this = bit_cast<fallback_uintptr>(p);
if (is_big_endian()) {
if (const_check(is_big_endian())) {
for (size_t i = 0, j = sizeof(void*) - 1; i < j; ++i, --j)
std::swap(value[i], value[j]);
}
Expand Down

0 comments on commit 3f6e0f1

Please sign in to comment.