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 //===----------------------------------------------------------------------===//
9 // UNSUPPORTED: !stdlib=libc++ && (c++03 || c++11 || c++14)
13 // constexpr basic_string_view substr(size_type pos = 0, size_type n = npos) const;
15 // Throws: out_of_range if pos > size().
16 // Effects: Determines the effective length rlen of the string to reference as the smaller of n and size() - pos.
17 // Returns: basic_string_view(data()+pos, rlen).
19 #include <string_view>
24 #include "test_macros.h"
26 template <typename CharT
>
27 void test1(std::basic_string_view
<CharT
> sv
, std::size_t n
, size_t pos
) {
28 std::basic_string_view
<CharT
> sv1
;
29 #ifdef TEST_HAS_NO_EXCEPTIONS
31 return; // would throw if exceptions were enabled
32 sv1
= sv
.substr(pos
, n
);
35 sv1
= sv
.substr(pos
, n
);
36 assert(pos
<= sv
.size());
37 } catch (const std::out_of_range
&) {
38 assert(pos
> sv
.size());
42 const std::size_t rlen
= std::min(n
, sv
.size() - pos
);
43 assert(sv1
.size() == rlen
);
44 for (std::size_t i
= 0; i
< rlen
; ++i
)
45 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
;
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 #ifndef TEST_HAS_NO_WIDE_CHARACTERS
79 test(L
"ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE");
85 #if TEST_STD_VER >= 11
86 test(u
"ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE");
91 test(U
"ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE");
99 constexpr std::string_view sv1
{"ABCDE", 5};
102 constexpr std::string_view sv2
= sv1
.substr(0, 3);
103 static_assert(sv2
.size() == 3, "");
104 static_assert(sv2
[0] == 'A', "");
105 static_assert(sv2
[1] == 'B', "");
106 static_assert(sv2
[2] == 'C', "");
110 constexpr std::string_view sv2
= sv1
.substr(3, 0);
111 static_assert(sv2
.size() == 0, "");
115 constexpr std::string_view sv2
= sv1
.substr(3, 3);
116 static_assert(sv2
.size() == 2, "");
117 static_assert(sv2
[0] == 'D', "");
118 static_assert(sv2
[1] == 'E', "");