xref: /llvm-project/libcxx/test/std/strings/basic.string/string.capacity/shrink_to_fit.pass.cpp (revision 786366b18fadc3d7c4f150e89ef49c165767a668)
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 // <string>
10 
11 // void shrink_to_fit(); // constexpr since C++20
12 
13 #include <string>
14 #include <cassert>
15 
16 #include "test_macros.h"
17 #include "min_allocator.h"
18 
19 template <class S>
20 TEST_CONSTEXPR_CXX20 void
21 test(S s)
22 {
23     typename S::size_type old_cap = s.capacity();
24     S s0 = s;
25     s.shrink_to_fit();
26     LIBCPP_ASSERT(s.__invariants());
27     assert(s == s0);
28     assert(s.capacity() <= old_cap);
29     assert(s.capacity() >= s.size());
30 }
31 
32 template <class S>
33 TEST_CONSTEXPR_CXX20 void test_string() {
34   S s;
35   test(s);
36 
37   s.assign(10, 'a');
38   s.erase(5);
39   test(s);
40 
41   s.assign(100, 'a');
42   s.erase(50);
43   test(s);
44 }
45 
46 TEST_CONSTEXPR_CXX20 bool test() {
47   test_string<std::string>();
48 #if TEST_STD_VER >= 11
49   test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char>>>();
50 #endif
51 
52   return true;
53 }
54 
55 int main(int, char**)
56 {
57   test();
58 #if TEST_STD_VER > 17
59   static_assert(test());
60 #endif
61 
62   return 0;
63 }
64