xref: /llvm-project/libcxx/test/std/strings/basic.string/string.ops/string.accessors/data.pass.cpp (revision 6e1dcc9335116f650d68cdbed12bbb34a99b2d9b)
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 // const charT* data() const; // constexpr since C++20
12 //       charT* data();   // C++17, constexpr since C++20
13 
14 #include <string>
15 #include <cassert>
16 
17 #include "test_macros.h"
18 #include "min_allocator.h"
19 
20 template <class S>
test_const(const S & s)21 TEST_CONSTEXPR_CXX20 void test_const(const S& s) {
22   typedef typename S::traits_type T;
23   const typename S::value_type* str = s.data();
24   if (s.size() > 0) {
25     assert(T::compare(str, &s[0], s.size()) == 0);
26     assert(T::eq(str[s.size()], typename S::value_type()));
27   } else
28     assert(T::eq(str[0], typename S::value_type()));
29 }
30 
31 template <class S>
test_nonconst(S & s)32 TEST_CONSTEXPR_CXX20 void test_nonconst(S& s) {
33   typedef typename S::traits_type T;
34   typename S::value_type* str = s.data();
35   if (s.size() > 0) {
36     assert(T::compare(str, &s[0], s.size()) == 0);
37     assert(T::eq(str[s.size()], typename S::value_type()));
38   } else
39     assert(T::eq(str[0], typename S::value_type()));
40 }
41 
42 template <class S>
test_string()43 TEST_CONSTEXPR_CXX20 void test_string() {
44   test_const(S(""));
45   test_const(S("abcde"));
46   test_const(S("abcdefghij"));
47   test_const(S("abcdefghijklmnopqrst"));
48 #if TEST_STD_VER > 14
49   {
50     S s1("");
51     test_nonconst(s1);
52     S s2("abcde");
53     test_nonconst(s2);
54     S s3("abcdefghij");
55     test_nonconst(s3);
56     S s4("abcdefghijklmnopqrst");
57     test_nonconst(s4);
58   }
59 #endif
60 }
61 
test()62 TEST_CONSTEXPR_CXX20 bool test() {
63   test_string<std::string>();
64 #if TEST_STD_VER >= 11
65   test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char> > >();
66 #endif
67 
68   return true;
69 }
70 
main(int,char **)71 int main(int, char**) {
72   test();
73 #if TEST_STD_VER > 17
74   static_assert(test());
75 #endif
76 
77   return 0;
78 }
79