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

A. Jiang via libcxx-commits libcxx-commits at lists.llvm.org
Fri Nov 15 02:23:49 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);
----------------
frederick-vs-ja wrote:

`std::allocator::allocate_at_least` (in all existing implementations) never performs over-allocation and just returns `{allocate(n), n}`. So the argument passed to the `allocator::deallocate` must be exactly the increased `n`. However, in order to meet the _Cpp17Allocator_ requirements, every value in `[old_n, new_n]` needs to be a valid argument for `increasing_allocator::deallocate`.

I guess if we want to emulate over-allocation with `std::allocator`, we should call `std::allocator<T>{}.allocate(DO_CEIL(n))` in **both** `allocate` and `allocate_at_least`, and call `std::allocator<T>{}.deallocate(p, DO_CEIL(n))` in `deallocate`, where `DO_CEIL` can be `std::bit_ceil` or something similar.

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


More information about the libcxx-commits mailing list