Add ctz to utils::algorithm

Use CTZ in bitset.forEachBitSet() so we can
efficiently go through them in order instead of
reverse order.
This commit is contained in:
Mathias Agopian
2018-08-17 16:54:50 -07:00
committed by Mathias Agopian
parent 0491c65517
commit 5ed80bc616
3 changed files with 71 additions and 1 deletions

View File

@@ -27,6 +27,11 @@ static inline T count_leading_zeros(T v) noexcept {
return utils::clz(v);
}
template <typename T>
static inline T count_trailing_zeros(T v) noexcept {
return utils::ctz(v);
}
TEST(AlgorithmTest, details_clz) {
for (uint64_t i = 1, j = 63; i < 64; i *= 2, j--) {
EXPECT_EQ(j, details::clz(i));
@@ -55,6 +60,28 @@ TEST(AlgorithmTest, clz) {
}
}
TEST(AlgorithmTest, details_ctz) {
for (uint64_t i = 1, j = 0; i < 64; i *= 2, j++) {
EXPECT_EQ(j, details::ctz(i));
}
for (uint32_t i = 1, j = 0; i < 32; i *= 2, j++) {
EXPECT_EQ(j, details::ctz(i));
}
}
TEST(AlgorithmTest, ctz) {
for (uint64_t i = 1, j = 0; i < 64; i *= 2, j++) {
EXPECT_EQ(j, ctz(i));
EXPECT_EQ(j, details::ctz(i));
EXPECT_EQ(j, count_trailing_zeros(i));
}
for (uint32_t i = 1, j = 0; i < 32; i *= 2, j++) {
EXPECT_EQ(j, ctz(i));
EXPECT_EQ(j, details::ctz(i));
EXPECT_EQ(j, count_trailing_zeros(i));
}
}
TEST(AlgorithmTest, details_popcount) {
EXPECT_EQ(0, details::popcount(0u));
EXPECT_EQ(0, details::popcount(0lu));