Skip to content

Commit 67752f6

Browse files
authored
[libc++] Simplify vector<bool>::__construct_at_end (#119632)
This patch simplifies the implementation of `__construct_at_end` in `vector<bool>`, which currently contains duplicate initialization logic across its two overloads.
1 parent 8a43d0e commit 67752f6

File tree

1 file changed

+10
-17
lines changed

1 file changed

+10
-17
lines changed

libcxx/include/__vector/vector_bool.h

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -552,36 +552,29 @@ vector<bool, _Allocator>::__recommend(size_type __new_size) const {
552552
}
553553

554554
// Default constructs __n objects starting at __end_
555-
// Precondition: __n > 0
556555
// Precondition: size() + __n <= capacity()
557556
// Postcondition: size() == size() + __n
558557
template <class _Allocator>
559558
inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void
560559
vector<bool, _Allocator>::__construct_at_end(size_type __n, bool __x) {
561-
size_type __old_size = this->__size_;
560+
_LIBCPP_ASSERT_INTERNAL(
561+
capacity() >= size() + __n, "vector<bool>::__construct_at_end called with insufficient capacity");
562+
std::fill_n(end(), __n, __x);
562563
this->__size_ += __n;
563-
if (__old_size == 0 || ((__old_size - 1) / __bits_per_word) != ((this->__size_ - 1) / __bits_per_word)) {
564-
if (this->__size_ <= __bits_per_word)
565-
this->__begin_[0] = __storage_type(0);
566-
else
567-
this->__begin_[(this->__size_ - 1) / __bits_per_word] = __storage_type(0);
568-
}
569-
std::fill_n(__make_iter(__old_size), __n, __x);
564+
if (end().__ctz_ != 0) // Ensure uninitialized leading bits in the last word are set to zero
565+
std::fill_n(end(), __bits_per_word - end().__ctz_, 0);
570566
}
571567

572568
template <class _Allocator>
573569
template <class _InputIterator, class _Sentinel>
574570
_LIBCPP_CONSTEXPR_SINCE_CXX20 void
575571
vector<bool, _Allocator>::__construct_at_end(_InputIterator __first, _Sentinel __last, size_type __n) {
576-
size_type __old_size = this->__size_;
572+
_LIBCPP_ASSERT_INTERNAL(
573+
capacity() >= size() + __n, "vector<bool>::__construct_at_end called with insufficient capacity");
574+
std::__copy(std::move(__first), std::move(__last), end());
577575
this->__size_ += __n;
578-
if (__old_size == 0 || ((__old_size - 1) / __bits_per_word) != ((this->__size_ - 1) / __bits_per_word)) {
579-
if (this->__size_ <= __bits_per_word)
580-
this->__begin_[0] = __storage_type(0);
581-
else
582-
this->__begin_[(this->__size_ - 1) / __bits_per_word] = __storage_type(0);
583-
}
584-
std::__copy(std::move(__first), std::move(__last), __make_iter(__old_size));
576+
if (end().__ctz_ != 0) // Ensure uninitialized leading bits in the last word are set to zero
577+
std::fill_n(end(), __bits_per_word - end().__ctz_, 0);
585578
}
586579

587580
template <class _Allocator>

0 commit comments

Comments
 (0)