[libcxx-commits] [libcxx] [libc++][test] Refactor increasing_allocator (PR #115671)

Peng Liu via libcxx-commits libcxx-commits at lists.llvm.org
Fri Nov 15 14:09:02 PST 2024


================
@@ -0,0 +1,43 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef INCREASING_ALLOCATOR_H
+#define INCREASING_ALLOCATOR_H
+
+#include <cstddef>
+#include <memory>
+
+#include "test_macros.h"
+
+#if TEST_STD_VER >= 23
+template <typename T>
+struct increasing_allocator {
+  using value_type         = T;
+  std::size_t min_elements = 1000;
+  increasing_allocator()   = default;
+
+  template <typename U>
+  constexpr increasing_allocator(const increasing_allocator<U>& other) noexcept : min_elements(other.min_elements) {}
+
+  constexpr std::allocation_result<T*> allocate_at_least(std::size_t n) {
+    if (n < min_elements)
+      n = min_elements;
+    min_elements += 1000;
+    return std::allocator<T>{}.allocate_at_least(n);
----------------
winner245 wrote:

This sounds like a very interesting approach to emulate over-allocation in `std::allocator::allocate_at_least`. Are you suggesting the following implementation?

```cpp
template <typename T>
struct bit_ceil_allocator {
  using value_type     = T; 
  bit_ceil_allocator() = default;

  template <typename U>
  constexpr bit_ceil_allocator(const bit_ceil_allocator<U>& other) noexcept {}

  constexpr std::allocation_result<T*> allocate_at_least(std::size_t n) { 
    n = std::bit_ceil(n);
    return std::allocator<T>{}.allocate_at_least(n);
  }

  constexpr T* allocate(std::size_t n) { 
    n = std::bit_ceil(n);
    return std::allocator<T>{}.allocate(n);
  }
  
  constexpr void deallocate(T* p, std::size_t n) noexcept { 
    std::allocator<T>{}.deallocate(p, std::bit_ceil(n)); 
  }
};
```

This implementation indeed performs over-allocation behind the scenes. It also appears to satisfy the _Cpp17Allocator_ requirements, which allows us to pass any value in `[n, std::bit_ceil(n)]` to `bit_ceil_allocator::deallocate`.

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


More information about the libcxx-commits mailing list