From 9fee7cdfcce00ce6500b8eebf67f4a6c91be98bd Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Mon, 17 Feb 2025 19:04:02 +0100 Subject: [PATCH] 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 Reviewed-by: Ivan Solovev --- src/corelib/text/qlocale.cpp | 8 +++++--- src/corelib/tools/qalgorithms.h | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/corelib/text/qlocale.cpp b/src/corelib/text/qlocale.cpp index ef1c9fe5a9a..01c48509342 100644 --- a/src/corelib/text/qlocale.cpp +++ b/src/corelib/text/qlocale.cpp @@ -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: diff --git a/src/corelib/tools/qalgorithms.h b/src/corelib/tools/qalgorithms.h index 44b9f030814..5b579c0938f 100644 --- a/src/corelib/tools/qalgorithms.h +++ b/src/corelib/tools/qalgorithms.h @@ -14,6 +14,7 @@ #if __has_include() && __cplusplus > 201703L #include #endif +#include #ifdef Q_CC_MSVC #include @@ -455,6 +456,21 @@ Result qJoin(InputIterator first, InputIterator last, Result init, const Separat return init; } +namespace QtPrivate { + +template +constexpr +std::enable_if_t, std::is_unsigned>, 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