| 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, c++17, c++20 |
| 10 | |
| 11 | // <memory> |
| 12 | |
| 13 | // template<class Allocator> |
| 14 | // [[nodiscard]] constexpr allocation_result<typename allocator_traits<Allocator>::pointer> |
| 15 | // allocate_at_least(Allocator& a, size_t n); |
| 16 | |
| 17 | #include <cassert> |
| 18 | #include <concepts> |
| 19 | #include <cstddef> |
| 20 | #include <memory> |
| 21 | |
| 22 | // check that std::allocation_result exists and isn't restricted to pointers |
| 23 | using AllocResult = std::allocation_result<int>; |
| 24 | |
| 25 | template <class T> |
| 26 | struct no_allocate_at_least { |
| 27 | using value_type = T; |
| 28 | T t; |
| 29 | |
| 30 | constexpr T* allocate(std::size_t) { return &t; } |
| 31 | constexpr void deallocate(T*, std::size_t) {} |
| 32 | }; |
| 33 | |
| 34 | template <class T> |
| 35 | struct has_allocate_at_least { |
| 36 | using value_type = T; |
| 37 | T t1; |
| 38 | T t2; |
| 39 | |
| 40 | constexpr T* allocate(std::size_t) { return &t1; } |
| 41 | constexpr void deallocate(T*, std::size_t) {} |
| 42 | constexpr std::allocation_result<T*> allocate_at_least(std::size_t) { return {&t2, 2}; } |
| 43 | }; |
| 44 | |
| 45 | constexpr bool test() { |
| 46 | { // check that std::allocate_at_least forwards to allocator::allocate if no allocate_at_least exists |
| 47 | no_allocate_at_least<int> alloc; |
| 48 | using AllocTraits = std::allocator_traits<decltype(alloc)>; |
| 49 | std::same_as<std::allocation_result<int*, AllocTraits::size_type>> decltype(auto) ret = |
| 50 | AllocTraits::allocate_at_least(alloc, 1); |
| 51 | assert(ret.count == 1); |
| 52 | assert(ret.ptr == &alloc.t); |
| 53 | } |
| 54 | |
| 55 | { // check that std::allocate_at_least forwards to allocator::allocate_at_least if allocate_at_least exists |
| 56 | has_allocate_at_least<int> alloc; |
| 57 | using AllocTraits = std::allocator_traits<decltype(alloc)>; |
| 58 | std::same_as<std::allocation_result<int*, AllocTraits::size_type>> decltype(auto) ret = |
| 59 | AllocTraits::allocate_at_least(alloc, 1); |
| 60 | assert(ret.count == 2); |
| 61 | assert(ret.ptr == &alloc.t2); |
| 62 | } |
| 63 | |
| 64 | return true; |
| 65 | } |
| 66 | |
| 67 | int main(int, char**) { |
| 68 | test(); |
| 69 | static_assert(test()); |
| 70 | |
| 71 | return 0; |
| 72 | } |
| 73 | |