Skip to content

Commit c5168d5

Browse files
committed
Refactor poor implementation for checking the number of digits in a number
1 parent 1365dbe commit c5168d5

File tree

1 file changed

+10
-26
lines changed

1 file changed

+10
-26
lines changed

src/assert.cpp

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1407,31 +1407,16 @@ namespace libassert::detail {
14071407
};
14081408

14091409
LIBASSERT_ATTR_COLD
1410-
static constexpr unsigned log10(unsigned n) {
1411-
if(n <= 1) {
1412-
return 1;
1413-
}
1414-
unsigned t = 1;
1415-
for(int i = 0; i < [] {
1416-
// was going to reuse `i` but https://bugs.llvm.org/show_bug.cgi?id=51986
1417-
int j = 0, v = std::numeric_limits<int>::max();
1418-
while(v /= 10) {
1419-
j++;
1420-
}
1421-
return j;
1422-
} () - 1; i++) {
1423-
if(n <= t) {
1424-
return i;
1425-
}
1426-
t *= 10;
1427-
}
1428-
return t;
1410+
static constexpr unsigned n_digits(unsigned value) {
1411+
return value < 10 ? 1 : 1 + n_digits(value / 10);
14291412
}
14301413

1431-
static_assert(log10(1) == 1);
1432-
static_assert(log10(9) == 1);
1433-
static_assert(log10(10) == 1);
1434-
static_assert(log10(11) == 2);
1414+
static_assert(n_digits(0) == 1);
1415+
static_assert(n_digits(1) == 1);
1416+
static_assert(n_digits(9) == 1);
1417+
static_assert(n_digits(10) == 2);
1418+
static_assert(n_digits(11) == 2);
1419+
static_assert(n_digits(1024) == 4);
14351420

14361421
using path_components = std::vector<std::string>;
14371422

@@ -1709,9 +1694,8 @@ namespace libassert::detail {
17091694
return a.line < b.line;
17101695
}
17111696
)->line;
1712-
// +1 for indices starting at 0, +1 again for log
1713-
const size_t max_line_number_width = log10(max_line_number + 1 + 1);
1714-
const size_t max_frame_width = log10(end - start + 1 + 1); // ^
1697+
const size_t max_line_number_width = n_digits(max_line_number);
1698+
const size_t max_frame_width = n_digits(end - start);
17151699
// do the actual trace
17161700
for(size_t i = start; i <= end; i++) {
17171701
const auto& [address, line, col, source_path, signature] = trace[i];

0 commit comments

Comments
 (0)