| 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 | // UNSUPPORTED: c++03, c++11, c++14 |
| 10 | // TODO: Change to XFAIL once https://github.com/llvm/llvm-project/issues/40340 is fixed |
| 11 | // UNSUPPORTED: availability-pmr-missing |
| 12 | |
| 13 | // <memory_resource> |
| 14 | |
| 15 | // class synchronized_pool_resource |
| 16 | |
| 17 | #include <memory_resource> |
| 18 | #include <cassert> |
| 19 | #include <memory> // std::align |
| 20 | |
| 21 | #include "count_new.h" |
| 22 | #include "test_macros.h" |
| 23 | |
| 24 | static bool is_aligned_to(void* p, std::size_t alignment) { |
| 25 | void* p2 = p; |
| 26 | std::size_t space = 1; |
| 27 | void* result = std::align(align: alignment, size: 1, ptr&: p2, space&: space); |
| 28 | return (result == p); |
| 29 | } |
| 30 | |
| 31 | int main(int, char**) { |
| 32 | globalMemCounter.reset(); |
| 33 | std::pmr::pool_options opts{.max_blocks_per_chunk: 1, .largest_required_pool_block: 256}; |
| 34 | auto sync1 = std::pmr::synchronized_pool_resource(opts, std::pmr::new_delete_resource()); |
| 35 | std::pmr::memory_resource& r1 = sync1; |
| 36 | |
| 37 | void* ret = r1.allocate(bytes: 8); |
| 38 | assert(ret != nullptr); |
| 39 | assert(is_aligned_to(ret, 8)); |
| 40 | ASSERT_WITH_LIBRARY_INTERNAL_ALLOCATIONS(globalMemCounter.checkNewCalledGreaterThan(0)); |
| 41 | int new_called = globalMemCounter.new_called; |
| 42 | |
| 43 | // After deallocation, the pool for 8-byte blocks should have at least one vacancy. |
| 44 | r1.deallocate(p: ret, bytes: 8); |
| 45 | assert(globalMemCounter.new_called == new_called); |
| 46 | assert(globalMemCounter.checkDeleteCalledEq(0)); |
| 47 | |
| 48 | // This should return an existing block from the pool: no new allocations. |
| 49 | ret = r1.allocate(bytes: 8); |
| 50 | assert(ret != nullptr); |
| 51 | assert(is_aligned_to(ret, 8)); |
| 52 | assert(globalMemCounter.new_called == new_called); |
| 53 | assert(globalMemCounter.checkDeleteCalledEq(0)); |
| 54 | |
| 55 | return 0; |
| 56 | } |
| 57 | |