Skip to content

Commit

Permalink
remove code duplication (#3448)
Browse files Browse the repository at this point in the history
* remove code duplication

* new interface for remove_trailing_zeros(uint32_t& n, int s = 0)

---------

Co-authored-by: Florimond Collette <4939681+florimondcollette@users.noreply.github.com>
  • Loading branch information
florimond-collette and florimond-collette committed May 18, 2023
1 parent 821f8cd commit 4ce086f
Showing 1 changed file with 4 additions and 20 deletions.
24 changes: 4 additions & 20 deletions include/fmt/format-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -1128,7 +1128,7 @@ bool is_left_endpoint_integer_shorter_interval(int exponent) noexcept {
}

// Remove trailing zeros from n and return the number of zeros removed (float)
FMT_INLINE int remove_trailing_zeros(uint32_t& n) noexcept {
FMT_INLINE int remove_trailing_zeros(uint32_t& n, int s = 0) noexcept {
FMT_ASSERT(n != 0, "");
// Modular inverse of 5 (mod 2^32): (mod_inv_5 * 5) mod 2^32 = 1.
// See https://github.com/fmtlib/fmt/issues/3163 for more details.
Expand All @@ -1137,7 +1137,6 @@ FMT_INLINE int remove_trailing_zeros(uint32_t& n) noexcept {
const uint32_t mod_inv_25 =
static_cast<uint32_t>(uint64_t(mod_inv_5) * mod_inv_5);

int s = 0;
while (true) {
auto q = rotr(n * mod_inv_25, 2);
if (q > max_value<uint32_t>() / 100) break;
Expand All @@ -1162,25 +1161,10 @@ FMT_INLINE int remove_trailing_zeros(uint64_t& n) noexcept {

// Is n is divisible by 10^8?
if ((nm.high() & ((1ull << (90 - 64)) - 1)) == 0 && nm.low() < magic_number) {
// If yes, work with the quotient.
// If yes, work with the quotient...
auto n32 = static_cast<uint32_t>(nm.high() >> (90 - 64));

const uint32_t mod_inv_5 = 0xcccccccd;
const uint32_t mod_inv_25 = mod_inv_5 * mod_inv_5;

int s = 8;
while (true) {
auto q = rotr(n32 * mod_inv_25, 2);
if (q > max_value<uint32_t>() / 100) break;
n32 = q;
s += 2;
}
auto q = rotr(n32 * mod_inv_5, 1);
if (q <= max_value<uint32_t>() / 10) {
n32 = q;
s |= 1;
}

// ... and use the 32 bit variant of the function
int s = remove_trailing_zeros(n32, 8);
n = n32;
return s;
}
Expand Down

0 comments on commit 4ce086f

Please sign in to comment.