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

Simplifying format_decimal() #2498

Merged
merged 2 commits into from
Sep 12, 2021
Merged
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
24 changes: 12 additions & 12 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -1049,11 +1049,19 @@ inline auto equal2(const char* lhs, const char* rhs) -> bool {
}

// Copies two characters from src to dst.
template <typename Char> void copy2(Char* dst, const char* src) {
*dst++ = static_cast<Char>(*src++);
*dst = static_cast<Char>(*src);
template <typename Char>
FMT_CONSTEXPR20 FMT_INLINE void copy2(Char* dst, const char* src) {
if (!is_constant_evaluated() && std::is_same<Char, char>::value) {
memcpy(dst, src, 2);
} else {
// We read both bytes before writing so that the compiler can do it in
// one pair of read/write instructions (even if Char aliases char)
char dc0 = *src++;
char dc1 = *src;
*dst++ = static_cast<Char>(dc0);
*dst = static_cast<Char>(dc1);
}
}
FMT_INLINE void copy2(char* dst, const char* src) { memcpy(dst, src, 2); }

template <typename Iterator> struct format_decimal_result {
Iterator begin;
Expand All @@ -1069,14 +1077,6 @@ FMT_CONSTEXPR20 auto format_decimal(Char* out, UInt value, int size)
FMT_ASSERT(size >= count_digits(value), "invalid digit count");
out += size;
Char* end = out;
if (is_constant_evaluated()) {
while (value >= 10) {
*--out = static_cast<Char>('0' + value % 10);
value /= 10;
}
*--out = static_cast<Char>('0' + value);
return {out, end};
}
while (value >= 100) {
// Integer division is slow so do it for a group of two digits instead
// of for every digit. The idea comes from the talk by Alexandrescu
Expand Down