xref: /llvm-project/libcxx/test/std/strings/basic.string/string.modifiers/string_assign/pointer.pass.cpp (revision c77cdbac9b121611121adf5806a99aff4812a40c)
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 // basic_string<charT,traits,Allocator>& assign(const charT* s); // constexpr since C++20
12 
13 #include <string>
14 #include <stdexcept>
15 #include <cassert>
16 
17 #include "test_macros.h"
18 #include "min_allocator.h"
19 
20 template <class S>
21 TEST_CONSTEXPR_CXX20 void test(S s, const typename S::value_type* str, S expected) {
22   s.assign(str);
23   LIBCPP_ASSERT(s.__invariants());
24   assert(s == expected);
25 }
26 
27 template <class S>
28 TEST_CONSTEXPR_CXX20 void test_string() {
29   test(S(), "", S());
30   test(S(), "12345", S("12345"));
31   test(S(), "12345678901234567890", S("12345678901234567890"));
32 
33   test(S("12345"), "", S());
34   test(S("12345"), "12345", S("12345"));
35   test(S("12345"), "1234567890", S("1234567890"));
36 
37   test(S("12345678901234567890"), "", S());
38   test(S("12345678901234567890"), "12345", S("12345"));
39   test(S("12345678901234567890"), "12345678901234567890", S("12345678901234567890"));
40 
41   // Starting from long string (no SSO)
42   test(S("1234512345678901234567890"), "", S());
43   test(S("1234512345678901234567890"), "12345", S("12345"));
44   test(S("1234512345678901234567890"), "12345678901234567890", S("12345678901234567890"));
45 }
46 
47 TEST_CONSTEXPR_CXX20 bool test() {
48   test_string<std::string>();
49 #if TEST_STD_VER >= 11
50   test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char>>>();
51 #endif
52 
53   { // test assignment to self
54     typedef std::string S;
55     S s_short = "123/";
56     S s_long  = "Lorem ipsum dolor sit amet, consectetur/";
57 
58     s_short.assign(s_short.c_str());
59     assert(s_short == "123/");
60     s_short.assign(s_short.c_str() + 2);
61     assert(s_short == "3/");
62 
63     s_long.assign(s_long.c_str() + 30);
64     assert(s_long == "nsectetur/");
65   }
66 
67   return true;
68 }
69 
70 int main(int, char**) {
71   test();
72 #if TEST_STD_VER > 17
73   static_assert(test());
74 #endif
75 
76   return 0;
77 }
78