Zrythm v2.0.0-DEV
a highly automated and intuitive digital audio workstation
Loading...
Searching...
No Matches
views.h
1// SPDX-FileCopyrightText: © 2025 Alexandros Theodotou <alex@zrythm.org>
2// SPDX-License-Identifier: LicenseRef-ZrythmLicense
3
4#pragma once
5
6#include <cstddef>
7#include <iterator>
8#include <ranges>
9#include <utility>
10
11namespace zrythm::utils::views
12{
13
14template <typename Iterator> class EnumerateIterator
15{
16public:
17 using iterator_category =
18 typename std::iterator_traits<Iterator>::iterator_category;
19 using value_type =
20 std::pair<std::size_t, typename std::iterator_traits<Iterator>::value_type>;
21 using difference_type =
22 typename std::iterator_traits<Iterator>::difference_type;
23 using pointer =
24 std::pair<std::size_t, typename std::iterator_traits<Iterator>::pointer>;
25 using reference =
26 std::pair<std::size_t, typename std::iterator_traits<Iterator>::reference>;
27
28 using ValueType =
29 std::pair<std::size_t, decltype (*std::declval<Iterator> ())>;
30
31 EnumerateIterator (Iterator it, std::size_t index = 0)
32 : index_ (index), it_ (it)
33 {
34 }
35
36 ValueType operator* () const { return { index_, *it_ }; }
37
38 EnumerateIterator &operator++ ()
39 {
40 ++index_;
41 ++it_;
42 return *this;
43 }
44 EnumerateIterator operator++ (int)
45 {
46 auto tmp = *this;
47 ++(*this);
48 return tmp;
49 }
50
51 bool operator== (const EnumerateIterator &other) const
52 {
53 return it_ == other.it_;
54 }
55 bool operator!= (const EnumerateIterator &other) const
56 {
57 return !(*this == other);
58 }
59
60 bool operator== (const Iterator &other) const { return it_ == other; }
61
62private:
63 std::size_t index_;
64 Iterator it_;
65};
66
67template <typename Range>
68class EnumerateView : public std::ranges::view_interface<EnumerateView<Range>>
69{
70 Range range_;
71
72public:
75
76 explicit EnumerateView (Range &&r) : range_ (std::forward<Range> (r)) { }
77
78 auto begin ()
79 {
80 using std::begin;
81 return EnumerateIterator (begin (range_), 0);
82 }
83
84 auto end ()
85 {
86 using std::end;
87 return EnumerateIterator (end (range_));
88 }
89};
90
91// Helper function to create the view
92template <std::ranges::viewable_range Range>
93auto
94enumerate (Range &&r)
95{
96 return EnumerateView<Range> (std::forward<Range> (r));
97}
98
99} // namespace zrythm::utils::views