xref: /llvm-project/libcxx/test/std/strings/basic.string/string.capacity/max_size.pass.cpp (revision 6e1dcc9335116f650d68cdbed12bbb34a99b2d9b)
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 // UNSUPPORTED: no-exceptions
10 // <string>
11 
12 // size_type max_size() const; // constexpr since C++20
13 
14 // NOTE: asan and msan will fail for one of two reasons
15 // 1. If allocator_may_return_null=0 then they will fail because the allocation
16 //    returns null.
17 // 2. If allocator_may_return_null=1 then they will fail because the allocation
18 //    is too large to succeed.
19 // UNSUPPORTED: sanitizer-new-delete
20 
21 #include <string>
22 #include <cassert>
23 #include <new>
24 
25 #include "test_macros.h"
26 #include "min_allocator.h"
27 
28 template <class S>
29 TEST_CONSTEXPR_CXX20 void test_resize_max_size_minus_1(const S& s) {
30   S s2(s);
31   const std::size_t sz = s2.max_size() - 1;
32   try {
33     s2.resize(sz, 'x');
34   } catch (const std::bad_alloc&) {
35     return;
36   }
37   assert(s2.size() == sz);
38 }
39 
40 template <class S>
41 TEST_CONSTEXPR_CXX20 void test_resize_max_size(const S& s) {
42   S s2(s);
43   const std::size_t sz = s2.max_size();
44   try {
45     s2.resize(sz, 'x');
46   } catch (const std::bad_alloc&) {
47     return;
48   }
49   assert(s.size() == sz);
50 }
51 
52 template <class S>
53 TEST_CONSTEXPR_CXX20 void test_string() {
54   {
55     S s;
56     assert(s.max_size() >= s.size());
57     assert(s.max_size() > 0);
58     if (!TEST_IS_CONSTANT_EVALUATED) {
59       test_resize_max_size_minus_1(s);
60       test_resize_max_size(s);
61     }
62   }
63   {
64     S s("123");
65     assert(s.max_size() >= s.size());
66     assert(s.max_size() > 0);
67     if (!TEST_IS_CONSTANT_EVALUATED) {
68       test_resize_max_size_minus_1(s);
69       test_resize_max_size(s);
70     }
71   }
72   {
73     S s("12345678901234567890123456789012345678901234567890");
74     assert(s.max_size() >= s.size());
75     assert(s.max_size() > 0);
76     if (!TEST_IS_CONSTANT_EVALUATED) {
77       test_resize_max_size_minus_1(s);
78       test_resize_max_size(s);
79     }
80   }
81 }
82 
83 TEST_CONSTEXPR_CXX20 bool test() {
84   test_string<std::string>();
85 #if TEST_STD_VER >= 11
86   test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char> > >();
87 #endif
88 
89   return true;
90 }
91 
92 int main(int, char**) {
93   test();
94 #if TEST_STD_VER >= 20
95   static_assert(test());
96 #endif
97 
98   return 0;
99 }
100