Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix endianness bug in write_digit2_separated #2699

Merged
merged 3 commits into from
Jan 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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