diff --git a/src/core/lib/compression/compression_internal.cc b/src/core/lib/compression/compression_internal.cc index 01dd6c75218..df7646d0f03 100644 --- a/src/core/lib/compression/compression_internal.cc +++ b/src/core/lib/compression/compression_internal.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(); } absl::optional diff --git a/src/core/lib/gprpp/bitset.h b/src/core/lib/gprpp/bitset.h index dded433d080..f88e8466f41 100644 --- a/src/core/lib/gprpp/bitset.h +++ b/src/core/lib/gprpp/bitset.h @@ -153,6 +153,18 @@ class BitSet { return true; } + template + typename std::enable_if::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; } diff --git a/test/core/gprpp/bitset_test.cc b/test/core/gprpp/bitset_test.cc index dd6204ecef1..3e463ed2d42 100644 --- a/test/core/gprpp/bitset_test.cc +++ b/test/core/gprpp/bitset_test.cc @@ -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(), 0); + EXPECT_EQ(make_bitset(true, false, false).ToInt(), 1); + EXPECT_EQ(make_bitset(false, true, false).ToInt(), 2); + EXPECT_EQ(make_bitset(true, true, false).ToInt(), 3); + EXPECT_EQ(make_bitset(false, false, true).ToInt(), 4); + EXPECT_EQ(make_bitset(true, false, true).ToInt(), 5); + EXPECT_EQ(make_bitset(false, true, true).ToInt(), 6); + EXPECT_EQ(make_bitset(true, true, true).ToInt(), 7); +} + TEST(EmptyBitSet, Empty) { BitSet<0> b; EXPECT_TRUE(b.all());