xref: /llvm-project/libcxx/test/std/strings/basic.string/string.capacity/reserve.pass.cpp (revision f520c1445f2d9cfb6153e3c125076aa6e3a76fc8)
1 //===----------------------------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // XFAIL: libcpp-no-exceptions
11 // <string>
12 
13 // void reserve(size_type res_arg=0);
14 
15 #include <string>
16 #include <stdexcept>
17 #include <cassert>
18 
19 #include "min_allocator.h"
20 
21 template <class S>
22 void
23 test(S s)
24 {
25     typename S::size_type old_cap = s.capacity();
26     S s0 = s;
27     s.reserve();
28     assert(s.__invariants());
29     assert(s == s0);
30     assert(s.capacity() <= old_cap);
31     assert(s.capacity() >= s.size());
32 }
33 
34 template <class S>
35 void
36 test(S s, typename S::size_type res_arg)
37 {
38     typename S::size_type old_cap = s.capacity();
39     S s0 = s;
40     try
41     {
42         s.reserve(res_arg);
43         assert(res_arg <= s.max_size());
44         assert(s == s0);
45         assert(s.capacity() >= res_arg);
46         assert(s.capacity() >= s.size());
47     }
48     catch (std::length_error&)
49     {
50         assert(res_arg > s.max_size());
51     }
52 }
53 
54 int main()
55 {
56     {
57     typedef std::string S;
58     {
59     S s;
60     test(s);
61 
62     s.assign(10, 'a');
63     s.erase(5);
64     test(s);
65 
66     s.assign(100, 'a');
67     s.erase(50);
68     test(s);
69     }
70     {
71     S s;
72     test(s, 5);
73     test(s, 10);
74     test(s, 50);
75     }
76     {
77     S s(100, 'a');
78     s.erase(50);
79     test(s, 5);
80     test(s, 10);
81     test(s, 50);
82     test(s, 100);
83     test(s, S::npos);
84     }
85     }
86 #if __cplusplus >= 201103L
87     {
88     typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S;
89     {
90     S s;
91     test(s);
92 
93     s.assign(10, 'a');
94     s.erase(5);
95     test(s);
96 
97     s.assign(100, 'a');
98     s.erase(50);
99     test(s);
100     }
101     {
102     S s;
103     test(s, 5);
104     test(s, 10);
105     test(s, 50);
106     }
107     {
108     S s(100, 'a');
109     s.erase(50);
110     test(s, 5);
111     test(s, 10);
112     test(s, 50);
113     test(s, 100);
114     test(s, S::npos);
115     }
116     }
117 #endif
118 }
119