xref: /llvm-project/libcxx/test/std/strings/basic.string/string.capacity/max_size.pass.cpp (revision 8c61114c53dcd6139a4a750925b91ed9bcf4178c)
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;
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 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 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 void
51 test(const S& s)
52 {
53     assert(s.max_size() >= s.size());
54     test1(s);
55     test2(s);
56 }
57 
58 int main(int, char**)
59 {
60     {
61     typedef std::string S;
62     test(S());
63     test(S("123"));
64     test(S("12345678901234567890123456789012345678901234567890"));
65     }
66 #if TEST_STD_VER >= 11
67     {
68     typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S;
69     test(S());
70     test(S("123"));
71     test(S("12345678901234567890123456789012345678901234567890"));
72     }
73 #endif
74 
75   return 0;
76 }
77