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: c++03, c++11, c++14, c++17, c++20 10 11 // template<container-compatible-range<charT> R> 12 // constexpr basic_string& assign_range(R&& rg); // C++23 13 14 #include <string> 15 16 #include "../../../../containers/sequences/insert_range_sequence_containers.h" 17 #include "test_macros.h" 18 19 // Tested cases: 20 // - different kinds of assignments (assigning an {empty/one-element/mid-sized/long range} to an 21 // {empty/one-element/full} container); 22 // - an exception is thrown when allocating new elements. 23 24 constexpr bool test_constexpr() { 25 for_all_iterators_and_allocators_constexpr<char, const char*>([]<class Iter, class Sent, class Alloc>() { 26 test_sequence_assign_range<std::basic_string<char, std::char_traits<char>, Alloc>, Iter, Sent>([](auto&& c) { 27 LIBCPP_ASSERT(c.__invariants()); 28 }); 29 }); 30 31 return true; 32 } 33 34 int main(int, char**) { 35 static_assert(test_constraints_assign_range<std::basic_string, char, int>()); 36 37 for_all_iterators_and_allocators<char, const char*>([]<class Iter, class Sent, class Alloc>() { 38 test_sequence_assign_range<std::basic_string<char, std::char_traits<char>, Alloc>, Iter, Sent>([](auto&& c) { 39 LIBCPP_ASSERT(c.__invariants()); 40 }); 41 }); 42 static_assert(test_constexpr()); 43 44 { // Check that `assign_range` returns a reference to the string. 45 std::string c; 46 static_assert(std::is_lvalue_reference_v<decltype(c.assign_range(FullContainer_Begin_EmptyRange<char>.input))>); 47 assert(&c.assign_range(FullContainer_Begin_EmptyRange<char>.input) == &c); 48 assert(&c.assign_range(FullContainer_Begin_OneElementRange<char>.input) == &c); 49 assert(&c.assign_range(FullContainer_Begin_MidRange<char>.input) == &c); 50 assert(&c.assign_range(FullContainer_Begin_LongRange<char>.input) == &c); 51 } 52 53 // Note: `test_assign_range_exception_safety_throwing_copy` doesn't apply because copying chars cannot throw. 54 { 55 #if !defined(TEST_HAS_NO_EXCEPTIONS) 56 // Note: the input string must be long enough to prevent SSO, otherwise the allocator won't be used. 57 std::string in(64, 'a'); 58 59 try { 60 ThrowingAllocator<char> alloc; 61 62 globalMemCounter.reset(); 63 std::basic_string<char, std::char_traits<char>, ThrowingAllocator<char>> c(alloc); 64 c.assign_range(in); 65 assert(false); // The function call above should throw. 66 67 } catch (int) { 68 assert(globalMemCounter.new_called == globalMemCounter.delete_called); 69 } 70 #endif 71 } 72 73 return 0; 74 } 75