xref: /llvm-project/libcxx/test/std/ranges/range.utility/range.subrange/ctor.range_size.pass.cpp (revision 5dfdac74cadd9483a66eb17e51dc632b554cccb1)
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 
11 // template<borrowed_range R>
12 //   requires convertible-to-non-slicing<iterator_t<R>, I> &&
13 //            convertible_to<sentinel_t<R>, S>
14 // constexpr subrange(R&& r, make-unsigned-like-t<iter_difference_t<I>> n)
15 //   requires (K == subrange_kind::sized);
16 
17 #include <ranges>
18 #include <cassert>
19 
20 struct BorrowedRange {
21   constexpr explicit BorrowedRange(int* b, int* e) : begin_(b), end_(e) { }
22   constexpr int* begin() const { return begin_; }
23   constexpr int* end() const { return end_; }
24 
25 private:
26   int* begin_;
27   int* end_;
28 };
29 
30 template <>
31 inline constexpr bool std::ranges::enable_borrowed_range<BorrowedRange> = true;
32 
33 constexpr bool test() {
34   int buff[] = {1, 2, 3, 4, 5, 6, 7, 8};
35   using Subrange = std::ranges::subrange<int*, int*, std::ranges::subrange_kind::sized>;
36 
37   // Test with an empty range
38   {
39     BorrowedRange range(buff, buff);
40     Subrange subrange(range, 0);
41     assert(subrange.size() == 0);
42   }
43 
44   // Test with non-empty ranges
45   {
46     BorrowedRange range(buff, buff + 1);
47     Subrange subrange(range, 1);
48     assert(subrange.size() == 1);
49   }
50   {
51     BorrowedRange range(buff, buff + 2);
52     Subrange subrange(range, 2);
53     assert(subrange[0] == 1);
54     assert(subrange[1] == 2);
55     assert(subrange.size() == 2);
56   }
57   {
58     BorrowedRange range(buff, buff + 8);
59     Subrange subrange(range, 8);
60     assert(subrange[0] == 1);
61     assert(subrange[1] == 2);
62     // ...
63     assert(subrange[7] == 8);
64     assert(subrange.size() == 8);
65   }
66 
67   return true;
68 }
69 
70 int main(int, char**) {
71   test();
72   static_assert(test());
73 
74   return 0;
75 }
76