xref: /llvm-project/libcxx/test/std/strings/basic.string/string.capacity/max_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 // 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 
24 #include "test_macros.h"
25 #include "min_allocator.h"
26 
27 template <class S>
28 TEST_CONSTEXPR_CXX20 void
29 test1(const S& s)
30 {
31     S s2(s);
32     const size_t sz = s2.max_size() - 1;
33     try { s2.resize(sz, 'x'); }
34     catch ( const std::bad_alloc & ) { return ; }
35     assert ( s2.size() ==  sz );
36 }
37 
38 template <class S>
39 TEST_CONSTEXPR_CXX20 void
40 test2(const S& s)
41 {
42     S s2(s);
43     const size_t sz = s2.max_size();
44     try { s2.resize(sz, 'x'); }
45     catch ( const std::bad_alloc & ) { return ; }
46     assert ( s.size() ==  sz );
47 }
48 
49 template <class S>
50 TEST_CONSTEXPR_CXX20 void
51 test(const S& s)
52 {
53     assert(s.max_size() >= s.size());
54     test1(s);
55     test2(s);
56 }
57 
58 template <class S>
59 TEST_CONSTEXPR_CXX20 void test_string() {
60   test(S());
61   test(S("123"));
62   test(S("12345678901234567890123456789012345678901234567890"));
63 }
64 
65 TEST_CONSTEXPR_CXX20 bool test() {
66   test_string<std::string>();
67 #if TEST_STD_VER >= 11
68   test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char>>>();
69 #endif
70 
71   return true;
72 }
73 
74 #if TEST_STD_VER > 17
75 constexpr bool test_constexpr() {
76   std::string str;
77 
78   size_t size = str.max_size();
79   assert(size > 0);
80 
81   return true;
82 }
83 #endif
84 
85 int main(int, char**)
86 {
87   test();
88 #if TEST_STD_VER > 17
89   test_constexpr();
90   static_assert(test_constexpr());
91 #endif
92 
93   return 0;
94 }
95