xref: /llvm-project/libcxx/test/std/strings/basic.string/string.capacity/shrink_to_fit.pass.cpp (revision 1cf4113952ae3e4cc75decdf6feb3ce5dd8ca4a1)
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 TEST_CONSTEXPR_CXX20 bool test() {
33   {
34     typedef std::string S;
35     S s;
36     test(s);
37 
38     s.assign(10, 'a');
39     s.erase(5);
40     test(s);
41 
42     s.assign(100, 'a');
43     s.erase(50);
44     test(s);
45   }
46 #if TEST_STD_VER >= 11
47   {
48     typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S;
49     S s;
50     test(s);
51 
52     s.assign(10, 'a');
53     s.erase(5);
54     test(s);
55 
56     s.assign(100, 'a');
57     s.erase(50);
58     test(s);
59   }
60 #endif
61 
62   return true;
63 }
64 
65 int main(int, char**)
66 {
67   test();
68 #if TEST_STD_VER > 17
69   static_assert(test());
70 #endif
71 
72   return 0;
73 }
74