Simplify QLocale::formattedDataSize()

- Introduce symbolic constants for the magic numbers 3 (= log10(base))
  and 10 (= log2(base)).

- Add and use QtPrivate::log2i() instead of manual bit fiddling. This
  makes the two cases nicely symmetric now.

Amends 9d23aebb271ea534a66cb3aceb2e63d9a1c870d6.

Pick-to: 6.9 6.8 6.5
Coverity-Id: 474294
Change-Id: I657f34878bc3a9b67b03a4d014b91e6d4de31e13
Reviewed-by: Shawn Rutledge <shawn.rutledge@qt.io>
Reviewed-by: Ivan Solovev <ivan.solovev@qt.io>
This commit is contained in:
Marc Mutz 2025-02-17 19:04:02 +01:00
parent 81bbbc3fc4
commit 9fee7cdfcc
2 changed files with 21 additions and 3 deletions

View File

@ -5052,9 +5052,11 @@ QString QLocale::formattedDataSize(qint64 bytes, int precision, DataSizeFormats
if (!bytes) {
power = 0;
} else if (format & DataSizeBase1000) {
power = int(std::log10(QtPrivate::qUnsignedAbs(bytes)) / 3);
} else { // Compute log2(bytes) / 10:
power = int((63 - qCountLeadingZeroBits(QtPrivate::qUnsignedAbs(bytes))) / 10);
constexpr auto log10_1000 = 3; // std::log10(1000U)
power = int(std::log10(QtPrivate::qUnsignedAbs(bytes))) / log10_1000;
} else {
constexpr auto log2_1024 = 10; // QtPrivate::log2i(1024U);
power = QtPrivate::log2i(QtPrivate::qUnsignedAbs(bytes)) / log2_1024;
base = 1024;
}
// Only go to doubles if we'll be using a quantifier:

View File

@ -14,6 +14,7 @@
#if __has_include(<bit>) && __cplusplus > 201703L
#include <bit>
#endif
#include <type_traits>
#ifdef Q_CC_MSVC
#include <intrin.h>
@ -455,6 +456,21 @@ Result qJoin(InputIterator first, InputIterator last, Result init, const Separat
return init;
}
namespace QtPrivate {
template <typename T>
constexpr
std::enable_if_t<std::conjunction_v<std::is_integral<T>, std::is_unsigned<T>>, int>
log2i(T x)
{
// Integral -> int version of std::log2():
Q_ASSERT(x > 0); // Q_PRE
// C++20: return std::bit_width(x) - 1
return int(sizeof(T) * 8 - 1 - qCountLeadingZeroBits(x));
}
} // namespace QtPrivate
QT_END_NAMESPACE
#endif // QALGORITHMS_H