From 9182190574617a2312b97bcaae6cdf69524350ed Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Wed, 18 Nov 2026 19:10:31 +0800 Subject: [PATCH] fix(utils): use a size_t shift operand in ceil_log2 `1UL` is 32 bits on LLP64 (64-bit Windows), so ceil_log2 shifted past the operand width for inputs of 2^32 or more. No library code calls it. Reported in #246. --- include/rabitqlib/utils/tools.hpp | 2 +- tests/unit/rabitqlib/utils/tools_test.cpp | 28 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 tests/unit/rabitqlib/utils/tools_test.cpp diff --git a/include/rabitqlib/utils/tools.hpp b/include/rabitqlib/utils/tools.hpp index 11ea3b29..b661f94f 100644 --- a/include/rabitqlib/utils/tools.hpp +++ b/include/rabitqlib/utils/tools.hpp @@ -77,7 +77,7 @@ inline size_t floor_log2(size_t x) { inline size_t ceil_log2(size_t x) { size_t ret = floor_log2(x); - return (1UL << ret) < x ? ret + 1 : ret; + return (size_t{1} << ret) < x ? ret + 1 : ret; } inline bool is_powerof2(size_t n) { return n > 0 && (n & (n - 1)) == 0; } diff --git a/tests/unit/rabitqlib/utils/tools_test.cpp b/tests/unit/rabitqlib/utils/tools_test.cpp new file mode 100644 index 00000000..bc012cf7 --- /dev/null +++ b/tests/unit/rabitqlib/utils/tools_test.cpp @@ -0,0 +1,28 @@ +#include "rabitqlib/utils/tools.hpp" + +#include + +#include +#include + +namespace rabitqlib { +namespace { + +TEST(ToolsTest, CeilLog2RoundsUpAcrossSizeTWidth) { + EXPECT_EQ(ceil_log2(0), 0U); + EXPECT_EQ(ceil_log2(1), 0U); + EXPECT_EQ(ceil_log2(3), 2U); + + // Exponents of 32 and above exceed the width of a 32-bit shift operand + // (unsigned long on LLP64). + constexpr size_t kDigits = std::numeric_limits::digits; + for (size_t bit = 1; bit < kDigits; ++bit) { + const size_t power = size_t{1} << bit; + EXPECT_EQ(ceil_log2(power), bit) << bit; + EXPECT_EQ(ceil_log2(power + 1), bit + 1) << bit; + } + EXPECT_EQ(ceil_log2(std::numeric_limits::max()), kDigits); +} + +} // namespace +} // namespace rabitqlib