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