Skip to content

Commit

Permalink
[libc++][vector] Fixes shrink_to_fit.
Browse files Browse the repository at this point in the history
This assures shrink_to_fit does not increase the allocated size.

Partly addresses #95161
  • Loading branch information
mordante committed Jul 6, 2024
1 parent f90bac9 commit c7f62ec
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
6 changes: 5 additions & 1 deletion libcxx/include/vector
Original file line number Diff line number Diff line change
Expand Up @@ -1443,7 +1443,11 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 void vector<_Tp, _Allocator>::shrink_to_fit() _NOE
#endif // _LIBCPP_HAS_NO_EXCEPTIONS
allocator_type& __a = this->__alloc();
__split_buffer<value_type, allocator_type&> __v(size(), size(), __a);
__swap_out_circular_buffer(__v);
// The Standard mandates shrink_to_fit() does not increase the capacity.
// With equal capacity keep the existing buffer. This avoids extra work
// due to swapping the elements.
if (__v.capacity() < capacity())
__swap_out_circular_buffer(__v);
#ifndef _LIBCPP_HAS_NO_EXCEPTIONS
} catch (...) {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,46 @@ TEST_CONSTEXPR_CXX20 bool tests() {
return true;
}

std::size_t min_bytes = 1000;

template <typename T>
struct increasing_allocator {
using value_type = T;
increasing_allocator() = default;
template <typename U>
increasing_allocator(const increasing_allocator<U>&) noexcept {}
std::allocation_result<T*> allocate_at_least(std::size_t n) {
std::size_t allocation_amount = n * sizeof(T);
if (allocation_amount < min_bytes)
allocation_amount = min_bytes;
min_bytes += 1000;
return {static_cast<T*>(::operator new(allocation_amount)), allocation_amount};
}
T* allocate(std::size_t n) { return allocate_at_least(n).ptr; }
void deallocate(T* p, std::size_t) noexcept { ::operator delete(static_cast<void*>(p)); }
};

template <typename T, typename U>
bool operator==(increasing_allocator<T>, increasing_allocator<U>) {
return true;
}

// https://github.com/llvm/llvm-project/issues/95161
void test_increasing_allocator() {
std::vector<int, increasing_allocator<int>> v;
v.push_back(1);
assert(is_contiguous_container_asan_correct(v));
std::size_t capacity = v.capacity();
v.shrink_to_fit();
assert(v.capacity() == capacity);
assert(v.size() == 1);
assert(is_contiguous_container_asan_correct(v));
}

int main(int, char**)
{
tests();
test_increasing_allocator();
#if TEST_STD_VER > 17
static_assert(tests());
#endif
Expand Down

0 comments on commit c7f62ec

Please sign in to comment.