P4C
The P4 Compiler
Loading...
Searching...
No Matches
range.h
1/*
2Copyright 2013-present Barefoot Networks, Inc.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17#ifndef LIB_RANGE_H_
18#define LIB_RANGE_H_
19
20#include <iostream>
21
22namespace P4 {
23
24template <class T>
25class RangeIter {
26 int incr;
27 T cur, fin;
28 explicit RangeIter(T end) : incr(0), cur(end), fin(end) {}
29
30 public:
31 RangeIter(T start, T end)
32 : incr(start <= end ? 1 : -1), cur(start), fin(static_cast<T>(end + incr)) {}
33 RangeIter begin() const { return *this; }
34 RangeIter end() const { return RangeIter(fin); }
35 T operator*() const { return cur; }
36 bool operator==(const RangeIter &a) const { return cur == a.cur; }
37 bool operator!=(const RangeIter &a) const { return cur != a.cur; }
38 RangeIter &operator++() {
39 cur = static_cast<T>(cur + incr);
40 return *this;
41 }
42 template <class U>
43 friend std::ostream &operator<<(std::ostream &, const RangeIter<U> &);
44};
45
46template <class T>
47static inline RangeIter<T> Range(T a, T b) {
48 return RangeIter<T>(a, b);
49}
50template <class T>
51static inline RangeIter<T> Range(std::pair<T, T> p) {
52 return RangeIter<T>(p.first, p.second);
53}
54template <class T>
55static inline RangeIter<T> ReverseRange(std::pair<T, T> p) {
56 return RangeIter<T>(p.second, p.first);
57}
58
59template <class T>
60std::ostream &operator<<(std::ostream &out, const RangeIter<T> &r) {
61 out << r.cur;
62 if (r.cur + r.incr != r.fin) out << ".." << (r.fin - r.incr);
63 return out;
64}
65
66} // namespace P4
67
68#endif /* LIB_RANGE_H_ */
Definition range.h:25
TODO: this is not really specific to BMV2, it should reside somewhere else.
Definition applyOptionsPragmas.cpp:24