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