P4C
The P4 Compiler
Loading...
Searching...
No Matches
iterator_range.h
1/*
2Licensed under the Apache License, Version 2.0 (the "License");
3you may not use this file except in compliance with the License.
4You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8Unless required by applicable law or agreed to in writing, software
9distributed under the License is distributed on an "AS IS" BASIS,
10WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11See the License for the specific language governing permissions and
12limitations under the License.
13*/
14
15#ifndef LIB_ITERATOR_RANGE_H_
16#define LIB_ITERATOR_RANGE_H_
17
18#include <iterator>
19#include <utility>
20
21namespace P4::Util {
22namespace Detail {
23using std::begin;
24using std::end;
25
26template <typename Container>
27using IterOfContainer = decltype(begin(std::declval<Container &>()));
28
29template <typename Range>
30constexpr auto begin_impl(Range &&range) {
31 return begin(std::forward<Range>(range));
32}
33
34template <typename Range>
35constexpr auto end_impl(Range &&range) {
36 return end(std::forward<Range>(range));
37}
38
39} // namespace Detail
40
41// This is a lightweight alternative for C++20 std::range. Should be replaced
42// with ranges as soon as C++20 would be implemented.
43template <typename Iter, typename Sentinel = Iter>
45 using reverse_iterator = std::reverse_iterator<Iter>;
46
47 Iter beginIt, endIt;
48
49 public:
50 template <typename Container>
51 explicit iterator_range(Container &&c)
52 : beginIt(Detail::begin_impl(c)), endIt(Detail::end_impl(c)) {}
53
54 iterator_range(Iter beginIt, Iter endIt)
55 : beginIt(std::move(beginIt)), endIt(std::move(endIt)) {}
56
57 auto reverse() const { return iterator_range<reverse_iterator>(rbegin(), rend()); }
58
59 auto begin() const { return beginIt; }
60 auto end() const { return endIt; }
61 auto rbegin() const { return reverse_iterator{endIt}; }
62 auto rend() const { return reverse_iterator{beginIt}; }
63
64 bool empty() const { return beginIt == endIt; }
65};
66
67template <typename Container>
69
70} // namespace P4::Util
71
72#endif /* LIB_ITERATOR_RANGE_H_ */
Definition iterator_range.h:44