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// size_type capacity() const; // constexpr since C++20
12
13#include <string>
14#include <cassert>
15
16#include "test_allocator.h"
17#include "min_allocator.h"
18#include "asan_testing.h"
19
20#include "test_macros.h"
21
22template <class S>
23TEST_CONSTEXPR_CXX20 void test_invariant(S s, test_allocator_statistics& alloc_stats) {
24 alloc_stats.throw_after = 0;
25#ifndef TEST_HAS_NO_EXCEPTIONS
26 try
27#endif
28 {
29 while (s.size() < s.capacity())
30 s.push_back(typename S::value_type());
31 assert(s.size() == s.capacity());
32 LIBCPP_ASSERT(is_string_asan_correct(s));
33 }
34#ifndef TEST_HAS_NO_EXCEPTIONS
35 catch (...) {
36 assert(false);
37 }
38#endif
39 alloc_stats.throw_after = INT_MAX;
40}
41
42template <class Alloc>
43TEST_CONSTEXPR_CXX20 void test_string(const Alloc& a) {
44 using S = std::basic_string<char, std::char_traits<char>, Alloc>;
45 {
46 S const s((Alloc(a)));
47 assert(s.capacity() >= 0);
48 LIBCPP_ASSERT(is_string_asan_correct(s));
49 }
50 {
51 S const s(3, 'x', Alloc(a));
52 assert(s.capacity() >= 3);
53 LIBCPP_ASSERT(is_string_asan_correct(s));
54 }
55#if TEST_STD_VER >= 11
56 // Check that we perform SSO
57 {
58 S const s;
59 assert(s.capacity() > 0);
60 ASSERT_NOEXCEPT(s.capacity());
61 LIBCPP_ASSERT(is_string_asan_correct(s));
62 }
63#endif
64}
65
66TEST_CONSTEXPR_CXX20 bool test() {
67 test_string(std::allocator<char>());
68 test_string(test_allocator<char>());
69 test_string(test_allocator<char>(3));
70 test_string(min_allocator<char>());
71 test_string(safe_allocator<char>());
72
73 {
74 test_allocator_statistics alloc_stats;
75 typedef std::basic_string<char, std::char_traits<char>, test_allocator<char> > S;
76 S s((test_allocator<char>(&alloc_stats)));
77 test_invariant(s, alloc_stats);
78 LIBCPP_ASSERT(is_string_asan_correct(s));
79 s.assign(10, 'a');
80 s.erase(5);
81 test_invariant(s, alloc_stats);
82 LIBCPP_ASSERT(is_string_asan_correct(s));
83 s.assign(100, 'a');
84 s.erase(50);
85 test_invariant(s, alloc_stats);
86 LIBCPP_ASSERT(is_string_asan_correct(s));
87 }
88
89 return true;
90}
91
92int main(int, char**) {
93 test();
94#if TEST_STD_VER >= 20
95 static_assert(test());
96#endif
97
98 return 0;
99}
100

source code of libcxx/test/std/strings/basic.string/string.capacity/capacity.pass.cpp