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 // UNSUPPORTED: c++03, c++11, c++14, c++17
10 // UNSUPPORTED: libcpp-no-concepts
11 // UNSUPPORTED: gcc-10
12 // UNSUPPORTED: libcpp-has-no-incomplete-ranges
13 
14 // Some basic examples of how drop_view might be used in the wild. This is a general
15 // collection of sample algorithms and functions that try to mock general usage of
16 // this view.
17 
18 #include <ranges>
19 
20 #include <vector>
21 #include <list>
22 #include <string>
23 
24 #include <cassert>
25 #include "test_macros.h"
26 #include "test_iterators.h"
27 #include "types.h"
28 
29 template<class T>
30 concept ValidDropView = requires { typename std::ranges::drop_view<T>; };
31 
32 static_assert( ValidDropView<ContiguousView>);
33 static_assert(!ValidDropView<Range>);
34 
35 static_assert(!std::ranges::enable_borrowed_range<std::ranges::drop_view<ContiguousView>>);
36 static_assert( std::ranges::enable_borrowed_range<std::ranges::drop_view<BorrowableView>>);
37 
38 template<std::ranges::view View>
39 bool orderedFibonacci(View v, int n = 1) {
40   if (v.size() < 3)
41     return true;
42 
43   if (v[2] != v[0] + v[1])
44     return false;
45 
46   return orderedFibonacci(std::ranges::drop_view(v.base(), n), n + 1);
47 }
48 
49 template<std::ranges::view View>
50 std::ranges::view auto makeEven(View v) {
51   return std::ranges::drop_view(v, v.size() % 2);
52 }
53 
54 template<std::ranges::view View, class T>
55 int indexOf(View v, T element) {
56   int index = 0;
57   for (auto e : v) {
58     if (e == element)
59       return index;
60     index++;
61   }
62   return -1;
63 }
64 
65 template<std::ranges::view View, class T>
66 std::ranges::view auto removeBefore(View v, T element) {
67   std::ranges::drop_view out(v, indexOf(v, element) + 1);
68   return View(out.begin(), out.end());
69 }
70 
71 template<>
72 constexpr bool std::ranges::enable_view<std::vector<int>> = true;
73 
74 template<>
75 constexpr bool std::ranges::enable_view<std::list<int>> = true;
76 
77 template<>
78 constexpr bool std::ranges::enable_view<std::string> = true;
79 
80 int main(int, char**) {
81   const std::vector vec = {1,1,2,3,5,8,13};
82   assert(orderedFibonacci(std::ranges::drop_view(vec, 0)));
83   const std::vector vec2 = {1,1,2,3,5,8,14};
84   assert(!orderedFibonacci(std::ranges::drop_view(vec2, 0)));
85 
86   const std::list l = {1, 2, 3};
87   auto el = makeEven(l);
88   assert(el.size() == 2);
89   assert(*el.begin() == 2);
90 
91   const std::string s = "Hello, World";
92   assert(removeBefore(s, ' ') == "World");
93 
94   return 0;
95 }
96