Skip to content

Commit

Permalink
Fix endianness bug in write_digit2_separated (#2699)
Browse files Browse the repository at this point in the history
* Fix endianness bug in write_digit2_separated

* Move endianness check to compile time if it possible

* Turn 8 into a constant
  • Loading branch information
phprus authored Jan 4, 2022
1 parent 17a5c80 commit 214cf13
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
10 changes: 9 additions & 1 deletion include/fmt/chrono.h
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,15 @@ 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);
memcpy(buf, &digits, 8);

constexpr const size_t len = 8;
if (const_check(is_big_endian())) {
char tmp[len];
memcpy(tmp, &digits, len);
std::reverse_copy(tmp, tmp + len, buf);
} else {
memcpy(buf, &digits, len);
}
}

template <typename Period> FMT_CONSTEXPR inline const char* get_units() {
Expand Down
10 changes: 9 additions & 1 deletion include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -296,10 +296,18 @@ FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To {
}

inline auto is_big_endian() -> bool {
#ifdef _WIN32
return false;
#elif defined(__BIG_ENDIAN__)
return true;
#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)
return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__;
#else
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.
Expand All @@ -309,7 +317,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 214cf13

Please sign in to comment.