xref: /llvm-project/libcxx/test/std/strings/basic.string/string.capacity/resize_size.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 resize(size_type n); // constexpr since C++20
12 
13 #include <string>
14 #include <stdexcept>
15 #include <cassert>
16 
17 #include "test_macros.h"
18 #include "min_allocator.h"
19 
20 template <class S>
21 TEST_CONSTEXPR_CXX20 void
22 test(S s, typename S::size_type n, S expected)
23 {
24     if (n <= s.max_size())
25     {
26         s.resize(n);
27         LIBCPP_ASSERT(s.__invariants());
28         assert(s == expected);
29     }
30 #ifndef TEST_HAS_NO_EXCEPTIONS
31     else if (!TEST_IS_CONSTANT_EVALUATED)
32     {
33         try
34         {
35             s.resize(n);
36             assert(false);
37         }
38         catch (std::length_error&)
39         {
40             assert(n > s.max_size());
41         }
42     }
43 #endif
44 }
45 
46 template <class S>
47 TEST_CONSTEXPR_CXX20 void test_string() {
48   test(S(), 0, S());
49   test(S(), 1, S(1, '\0'));
50   test(S(), 10, S(10, '\0'));
51   test(S(), 100, S(100, '\0'));
52   test(S("12345"), 0, S());
53   test(S("12345"), 2, S("12"));
54   test(S("12345"), 5, S("12345"));
55   test(S("12345"), 15, S("12345\0\0\0\0\0\0\0\0\0\0", 15));
56   test(S("12345678901234567890123456789012345678901234567890"), 0, S());
57   test(S("12345678901234567890123456789012345678901234567890"), 10,
58         S("1234567890"));
59   test(S("12345678901234567890123456789012345678901234567890"), 50,
60         S("12345678901234567890123456789012345678901234567890"));
61   test(S("12345678901234567890123456789012345678901234567890"), 60,
62         S("12345678901234567890123456789012345678901234567890\0\0\0\0\0\0\0\0\0\0", 60));
63   test(S(), S::npos, S("not going to happen"));
64 }
65 
66 TEST_CONSTEXPR_CXX20 bool test() {
67   test_string<std::string>();
68 #if TEST_STD_VER >= 11
69   test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char>>>();
70 #endif
71 
72   return true;
73 }
74 
75 int main(int, char**)
76 {
77   test();
78 #if TEST_STD_VER > 17
79   static_assert(test());
80 #endif
81 
82   return 0;
83 }
84