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 // <vector> 10 11 // void shrink_to_fit(); 12 13 #include <cassert> 14 #include <vector> 15 16 #include "asan_testing.h" 17 #include "increasing_allocator.h" 18 #include "min_allocator.h" 19 #include "test_allocator.h" 20 #include "test_macros.h" 21 22 TEST_CONSTEXPR_CXX20 bool tests() { 23 { 24 std::vector<int> v(100); 25 v.push_back(1); 26 assert(is_contiguous_container_asan_correct(v)); 27 v.shrink_to_fit(); 28 assert(v.capacity() == 101); 29 assert(v.size() == 101); 30 assert(is_contiguous_container_asan_correct(v)); 31 } 32 { 33 std::vector<int, limited_allocator<int, 401> > v(100); 34 v.push_back(1); 35 assert(is_contiguous_container_asan_correct(v)); 36 v.shrink_to_fit(); 37 assert(v.capacity() == 101); 38 assert(v.size() == 101); 39 assert(is_contiguous_container_asan_correct(v)); 40 } 41 #ifndef TEST_HAS_NO_EXCEPTIONS 42 if (!TEST_IS_CONSTANT_EVALUATED) { 43 std::vector<int, limited_allocator<int, 400> > v(100); 44 v.push_back(1); 45 assert(is_contiguous_container_asan_correct(v)); 46 v.shrink_to_fit(); 47 LIBCPP_ASSERT(v.capacity() == 200); // assumes libc++'s 2x growth factor 48 assert(v.size() == 101); 49 assert(is_contiguous_container_asan_correct(v)); 50 } 51 #endif 52 #if TEST_STD_VER >= 11 53 { 54 std::vector<int, min_allocator<int>> v(100); 55 v.push_back(1); 56 assert(is_contiguous_container_asan_correct(v)); 57 v.shrink_to_fit(); 58 assert(v.capacity() == 101); 59 assert(v.size() == 101); 60 assert(is_contiguous_container_asan_correct(v)); 61 } 62 { 63 std::vector<int, safe_allocator<int>> v(100); 64 v.push_back(1); 65 assert(is_contiguous_container_asan_correct(v)); 66 v.shrink_to_fit(); 67 assert(v.capacity() == 101); 68 assert(v.size() == 101); 69 assert(is_contiguous_container_asan_correct(v)); 70 } 71 #endif 72 73 return true; 74 } 75 76 #if TEST_STD_VER >= 23 77 // https://github.com/llvm/llvm-project/issues/95161 78 constexpr bool test_increasing_allocator() { 79 std::vector<int, increasing_allocator<int>> v; 80 v.push_back(1); 81 assert(is_contiguous_container_asan_correct(v)); 82 std::size_t capacity = v.capacity(); 83 v.shrink_to_fit(); 84 assert(v.capacity() <= capacity); 85 assert(v.size() == 1); 86 assert(is_contiguous_container_asan_correct(v)); 87 88 return true; 89 } 90 #endif // TEST_STD_VER >= 23 91 92 int main(int, char**) { 93 tests(); 94 #if TEST_STD_VER > 17 95 static_assert(tests()); 96 #endif 97 #if TEST_STD_VER >= 23 98 test_increasing_allocator(); 99 static_assert(test_increasing_allocator()); 100 #endif 101 102 return 0; 103 } 104