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