[libcxx-commits] [libcxx] [libc++][vector] Fixes shrink_to_fit. (PR #97895)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Mon Jul 15 08:57:21 PDT 2024


================
@@ -71,9 +71,50 @@ TEST_CONSTEXPR_CXX20 bool tests() {
     return true;
 }
 
+#if TEST_STD_VER >= 23
+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/sizeof(T)};
+  }
+  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)); }
+};
----------------
ldionne wrote:

```suggestion
template <typename T>
struct increasing_allocator {
  using value_type       = T;
  std::size_t min_elements = 100;
  increasing_allocator() = default;
  template <typename U>
  increasing_allocator(const increasing_allocator<U>& other) noexcept : min_elements(other.min_elements) {}
  std::allocation_result<T*> allocate_at_least(std::size_t n) {
    if (n < min_elements)
      n = min_elements;
    min_elements += 100;
    return std::allocator<T>().allocate_at_least(n);
  }
  T* allocate(std::size_t n) { return allocate_at_least(n).ptr; }
  void deallocate(T* p, std::size_t n) noexcept { std::allocator<T>::deallocate(p, n); }
};
```

That way, you can also run these tests inside `constexpr`.

https://github.com/llvm/llvm-project/pull/97895


More information about the libcxx-commits mailing list