Skip to content

Commit

Permalink
Merge pull request #106 from elbeno/bitset-difference
Browse files Browse the repository at this point in the history
Add bitset `operator-` (set difference)
  • Loading branch information
bdeane-intel authored Jun 3, 2024
2 parents 44c5b74 + 7e45a91 commit d2c0ba3
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
3 changes: 3 additions & 0 deletions docs/bitset.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,6 @@ auto bs = stdx::bitset<11>{0b101}; // 11 bits, value 5
auto i = bs.to<std::uint64_t>(); // 5 (a std::uint64_t)
auto j = bs.to_natural(); // 5 (a std::uint16_t)
----

Bitsets support all the usual bitwise operators (`and`, `or`, `xor` and `not`)
and also support `operator-` meaning set difference, or `a & ~b`.
5 changes: 5 additions & 0 deletions include/stdx/bitset.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ template <std::size_t N, typename StorageElem> class bitset {
return lhs;
}

friend constexpr auto operator-(bitset const &lhs, bitset rhs) -> bitset {
rhs.flip();
return lhs & rhs;
}

friend constexpr auto operator<<(bitset lhs, std::size_t pos) -> bitset {
lhs <<= pos;
return lhs;
Expand Down
7 changes: 7 additions & 0 deletions test/bitset.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,13 @@ TEMPLATE_TEST_CASE("not", "[bitset]", std::uint8_t, std::uint16_t,
static_assert(~bs == stdx::bitset<3, TestType>{0b10ul});
}

TEMPLATE_TEST_CASE("difference", "[bitset]", std::uint8_t, std::uint16_t,
std::uint32_t, std::uint64_t) {
constexpr auto bs1 = stdx::bitset<3, TestType>{0b101ul};
constexpr auto bs2 = stdx::bitset<3, TestType>{0b011ul};
static_assert(bs1 - bs2 == stdx::bitset<3, TestType>{0b100ul});
}

TEMPLATE_TEST_CASE("left shift", "[bitset]", std::uint8_t, std::uint16_t,
std::uint32_t, std::uint64_t) {
constexpr auto bs = stdx::bitset<3, TestType>{0b101ul};
Expand Down

0 comments on commit d2c0ba3

Please sign in to comment.