1 //===----------------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
11 // constexpr basic_string_view substr(size_type pos = 0, size_type n = npos) const;
13 // Throws: out_of_range if pos > size().
14 // Effects: Determines the effective length rlen of the string to reference as the smaller of n and size() - pos.
15 // Returns: basic_string_view(data()+pos, rlen).
17 #include <string_view>
22 #include "test_macros.h"
24 template<typename CharT
>
25 void test1(std::basic_string_view
<CharT
> sv
, size_t n
, size_t pos
) {
26 std::basic_string_view
<CharT
> sv1
;
27 #ifdef TEST_HAS_NO_EXCEPTIONS
29 return ; // would throw if exceptions were enabled
30 sv1
= sv
.substr(pos
, n
);
33 sv1
= sv
.substr(pos
, n
);
34 assert(pos
<= sv
.size());
36 catch (const std::out_of_range
&) {
37 assert(pos
> sv
.size());
41 const size_t rlen
= std::min(n
, sv
.size() - pos
);
42 assert (sv1
.size() == rlen
);
43 for (size_t i
= 0; i
< rlen
; ++i
)
44 assert(sv
[pos
+i
] == sv1
[i
]);
48 template<typename CharT
>
49 void test ( const CharT
*s
) {
50 typedef std::basic_string_view
<CharT
> string_view_t
;
52 string_view_t
sv1 ( s
);
57 test1(sv1
, sv1
.size(), 0);
63 test1(sv1
, 0, string_view_t::npos
);
64 test1(sv1
, 2, string_view_t::npos
);
65 test1(sv1
, sv1
.size(), string_view_t::npos
);
67 test1(sv1
, sv1
.size() + 1, 0);
68 test1(sv1
, sv1
.size() + 1, 1);
69 test1(sv1
, sv1
.size() + 1, string_view_t::npos
);
72 int main(int, char**) {
73 test ( "ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE" );
78 test ( L
"ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE" );
83 #if TEST_STD_VER >= 11
84 test ( u
"ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE" );
89 test ( U
"ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE" );
97 constexpr std::string_view sv1
{ "ABCDE", 5 };
100 constexpr std::string_view sv2
= sv1
.substr ( 0, 3 );
101 static_assert ( sv2
.size() == 3, "" );
102 static_assert ( sv2
[0] == 'A', "" );
103 static_assert ( sv2
[1] == 'B', "" );
104 static_assert ( sv2
[2] == 'C', "" );
108 constexpr std::string_view sv2
= sv1
.substr ( 3, 0 );
109 static_assert ( sv2
.size() == 0, "" );
113 constexpr std::string_view sv2
= sv1
.substr ( 3, 3 );
114 static_assert ( sv2
.size() == 2, "" );
115 static_assert ( sv2
[0] == 'D', "" );
116 static_assert ( sv2
[1] == 'E', "" );