xref: /llvm-project/libcxx/test/support/increasing_allocator.h (revision a821937b6d29f874d2561c6ef073faeed302b1a9)
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef TEST_SUPPORT_INCREASING_ALLOCATOR_H
10 #define TEST_SUPPORT_INCREASING_ALLOCATOR_H
11 
12 #include <cstddef>
13 #include <memory>
14 
15 #include "test_macros.h"
16 
17 // The increasing_allocator is a custom allocator that enforces an increasing minimum allocation size,
18 // ensuring that it allocates an increasing amount of memory, possibly exceeding the requested amount.
19 // This unique behavior is particularly useful for testing the shrink_to_fit functionality in std::vector,
20 // vector<bool>, and std::basic_string, ensuring that shrink_to_fit does not increase the capacity of
21 // the allocated memory.
22 
23 template <typename T>
24 struct increasing_allocator {
25   using value_type         = T;
26   std::size_t min_elements = 1000;
27   increasing_allocator()   = default;
28 
29   template <typename U>
30   TEST_CONSTEXPR_CXX20 increasing_allocator(const increasing_allocator<U>& other) TEST_NOEXCEPT
31       : min_elements(other.min_elements) {}
32 
33 #if TEST_STD_VER >= 23
34   TEST_CONSTEXPR_CXX23 std::allocation_result<T*> allocate_at_least(std::size_t n) {
35     if (n < min_elements)
36       n = min_elements;
37     min_elements += 1000;
38     return std::allocator<T>{}.allocate_at_least(n);
39   }
40 #endif // TEST_STD_VER >= 23
41 
42   TEST_CONSTEXPR_CXX20 T* allocate(std::size_t n) { return std::allocator<T>().allocate(n); }
43 
44   TEST_CONSTEXPR_CXX20 void deallocate(T* p, std::size_t n) TEST_NOEXCEPT { std::allocator<T>().deallocate(p, n); }
45 };
46 
47 template <typename T, typename U>
48 TEST_CONSTEXPR_CXX20 bool operator==(increasing_allocator<T>, increasing_allocator<U>) TEST_NOEXCEPT {
49   return true;
50 }
51 
52 #endif // TEST_SUPPORT_INCREASING_ALLOCATOR_H
53