Debian Codegraph @

libstdc++-v3/testsuite/std/ranges/adaptors/conditionally_borrowed.cc

raw
1 // Copyright (C) 2020-2025 Free Software Foundation, Inc.
2 //
3 // This file is part of the GNU ISO C++ Library. This library is free
4 // software; you can redistribute it and/or modify it under the
5 // terms of the GNU General Public License as published by the
6 // Free Software Foundation; either version 3, or (at your option)
7 // any later version.
8
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13
14 // You should have received a copy of the GNU General Public License along
15 // with this library; see the file COPYING3. If not see
16 // <http://www.gnu.org/licenses/>.
17
18 // { dg-do run { target c++20 } }
19
20 #include <ranges>
21 #include <algorithm>
22 #include <string>
23 #include <cctype>
24 #include <testsuite_hooks.h>
25
26 namespace ranges = std::ranges;
27 namespace views = std::views;
28 using namespace std::literals;
29
30 // P2017R1 "Conditionally borrowed ranges"
31 auto trim(std::string const& s) {
32 auto isalpha = [](unsigned char c){ return std::isalpha(c); };
33 auto b = ranges::find_if(s, isalpha);
34 auto e = ranges::find_if(s | views::reverse, isalpha).base();
35 return ranges::subrange(b, e);
36 }
37
38 void
39 test01()
40 {
41 VERIFY( ranges::equal( trim(" abc "), "abc"sv ) );
42
43 std::string s = "0123456789";
44 auto odd = [](char c){ return (c - '0') % 2; };
45 using namespace std::views;
46 auto pos = ranges::find(s | take(5) | drop(1) | drop_while(odd), '2');
47 VERIFY( *pos == '2' );
48
49 static_assert( ranges::borrowed_range<decltype(s | reverse)> );
50 static_assert( ranges::borrowed_range<decltype(s | take(1))> );
51 static_assert( ranges::borrowed_range<decltype(s | drop(1))> );
52 static_assert( ranges::borrowed_range<decltype(s | drop_while(odd))> );
53
54 ranges::subrange r(s.begin(), s.cend());
55 static_assert( !ranges::common_range<decltype(r)> );
56 auto pos2 = ranges::find(r | views::common, '2');
57 VERIFY( *pos2 == '2' );
58 }
59
60 void
61 test02()
62 {
63 std::pair<int, std::string_view> a[2]{ {1,"two"}, {3,"four"}};
64 // FIXME: We should be able to get rid of the decay via the + here.
65 // But we'd end up comparing two array types in equality_comparable_with
66 // -> __weakly_eq_cmp_with which is ill-formed in C++26 due to P2865.
67 auto pos = ranges::find(a | views::values, +"four");
68 VERIFY( *pos == "four" );
69
70 static_assert( ranges::borrowed_range<decltype(a | views::keys)> );
71 }
72
73 int main()
74 {
75 test01();
76 test02();
77 }