Skip to content

Commit

Permalink
Simplify flip() for std::bit_set
Browse files Browse the repository at this point in the history
  • Loading branch information
winner245 committed Dec 21, 2024
1 parent c1e7e45 commit cda3842
Show file tree
Hide file tree
Showing 3 changed files with 152 additions and 139 deletions.
18 changes: 3 additions & 15 deletions libcxx/include/bitset
Original file line number Diff line number Diff line change
Expand Up @@ -319,18 +319,8 @@ __bitset<_N_words, _Size>::operator^=(const __bitset& __v) _NOEXCEPT {

template <size_t _N_words, size_t _Size>
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 void __bitset<_N_words, _Size>::flip() _NOEXCEPT {
// do middle whole words
size_type __n = _Size;
__storage_pointer __p = __first_;
for (; __n >= __bits_per_word; ++__p, __n -= __bits_per_word)
*__p = ~*__p;
// do last partial word
if (__n > 0) {
__storage_type __m = ~__storage_type(0) >> (__bits_per_word - __n);
__storage_type __b = *__p & __m;
*__p &= ~__m;
*__p |= ~__b & __m;
}
for (size_type __i = 0; __i < _N_words; ++__i)
__first_[__i] = ~__first_[__i];
}

template <size_t _N_words, size_t _Size>
Expand Down Expand Up @@ -512,9 +502,7 @@ __bitset<1, _Size>::operator^=(const __bitset& __v) _NOEXCEPT {

template <size_t _Size>
inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 void __bitset<1, _Size>::flip() _NOEXCEPT {
__storage_type __m = ~__storage_type(0) >> (__bits_per_word - _Size);
__first_ = ~__first_;
__first_ &= __m;
__first_ = ~__first_;
}

template <size_t _Size>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,21 @@

template <std::size_t N>
TEST_CONSTEXPR_CXX23 void test_flip_all() {
std::vector<std::bitset<N> > const cases = get_test_cases<N>();
for (std::size_t c = 0; c != cases.size(); ++c) {
std::bitset<N> v1 = cases[c];
std::bitset<N> v2 = v1;
v2.flip();
for (std::size_t i = 0; i < v1.size(); ++i)
assert(v2[i] == ~v1[i]);
}
std::vector<std::bitset<N> > const cases = get_test_cases<N>();
for (std::size_t c = 0; c != cases.size(); ++c) {
std::bitset<N> v1 = cases[c];
std::bitset<N> v2 = v1;
v2.flip();
for (std::size_t i = 0; i < v1.size(); ++i)
assert(v2[i] == ~v1[i]);
}
}

TEST_CONSTEXPR_CXX23 bool test() {
test_flip_all<0>();
test_flip_all<1>();
test_flip_all<2>();
test_flip_all<5>();
test_flip_all<31>();
test_flip_all<32>();
test_flip_all<33>();
Expand Down
Loading

0 comments on commit cda3842

Please sign in to comment.