Add int conversions to bitset (#29246)

* Better int conversion

* add test
pull/29299/head
Craig Tiller 3 years ago committed by GitHub
parent 91cf96c6ee
commit ec1aa1f26c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 8
      src/core/lib/compression/compression_internal.cc
  2. 12
      src/core/lib/gprpp/bitset.h
  3. 18
      test/core/gprpp/bitset_test.cc

@ -194,13 +194,7 @@ CompressionAlgorithmSet CompressionAlgorithmSet::FromString(
}
uint32_t CompressionAlgorithmSet::ToLegacyBitmask() const {
uint32_t x = 0;
for (size_t i = 0; i < GRPC_COMPRESS_ALGORITHMS_COUNT; i++) {
if (set_.is_set(i)) {
x |= (1u << i);
}
}
return x;
return set_.ToInt<uint32_t>();
}
absl::optional<grpc_compression_algorithm>

@ -153,6 +153,18 @@ class BitSet {
return true;
}
template <typename Int>
typename std::enable_if<std::is_unsigned<Int>::value &&
(sizeof(Int) * 8 >= kTotalBits),
Int>::type
ToInt() const {
Int result = 0;
for (size_t i = 0; i < kTotalBits; i++) {
if (is_set(i)) result |= (Int(1) << i);
}
return result;
}
private:
// Given a bit index, return which unit it's stored in.
static constexpr size_t unit_for(size_t bit) { return bit / kUnitBits; }

@ -90,6 +90,24 @@ TYPED_TEST(BitSetTest, Count) {
}
}
TEST(ToIntTest, ToInt) {
auto make_bitset = [](bool b0, bool b1, bool b2) {
BitSet<3> b;
b.set(0, b0);
b.set(1, b1);
b.set(2, b2);
return b;
};
EXPECT_EQ(make_bitset(false, false, false).ToInt<uint32_t>(), 0);
EXPECT_EQ(make_bitset(true, false, false).ToInt<uint32_t>(), 1);
EXPECT_EQ(make_bitset(false, true, false).ToInt<uint32_t>(), 2);
EXPECT_EQ(make_bitset(true, true, false).ToInt<uint32_t>(), 3);
EXPECT_EQ(make_bitset(false, false, true).ToInt<uint32_t>(), 4);
EXPECT_EQ(make_bitset(true, false, true).ToInt<uint32_t>(), 5);
EXPECT_EQ(make_bitset(false, true, true).ToInt<uint32_t>(), 6);
EXPECT_EQ(make_bitset(true, true, true).ToInt<uint32_t>(), 7);
}
TEST(EmptyBitSet, Empty) {
BitSet<0> b;
EXPECT_TRUE(b.all());

Loading…
Cancel
Save