P4C
The P4 Compiler
Loading...
Searching...
No Matches
algorithm.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_ALGORITHM_H_
18#define LIB_ALGORITHM_H_
19
20#include <algorithm>
21#include <set>
22
23// Round up x/y, for integers
24#define ROUNDUP(x, y) (((x) + (y) - 1) / (y))
25// Elements in an array
26#define ELEMENTS(a) (sizeof(a) / sizeof(a[0]))
27
28/* these should all be in <algorithm>, but are missing... */
29namespace P4 {
30
31template <class C, class T>
32inline bool contains(C &c, const T &val) {
33 return std::find(c.begin(), c.end(), val) != c.end();
34}
35
36template <class C, class Pred>
37inline bool contains_if(C &c, Pred pred) {
38 return std::find_if(c.begin(), c.end(), pred) != c.end();
39}
40
41template <class C, class Pred>
42inline void erase_if(C &c, Pred pred) {
43 for (auto it = c.begin(); it != c.end();) {
44 if (pred(*it))
45 it = c.erase(it);
46 else
47 ++it;
48 }
49}
50
51template <class C, class Pred>
52inline void remove_if(C &c, Pred pred) {
53 c.erase(std::remove_if(c.begin(), c.end(), pred), c.end());
54}
55
56template <class C, class T>
57inline typename C::iterator find(C &c, const T &val) {
58 return std::find(c.begin(), c.end(), val);
59}
60
61using std::max_element;
62using std::min_element;
63
64template <class C>
65inline typename C::const_iterator min_element(const C &c) {
66 return min_element(c.begin(), c.end());
67}
68template <class C, class Compare>
69inline typename C::const_iterator min_element(const C &c, Compare comp) {
70 return min_element(c.begin(), c.end(), comp);
71}
72
73template <class C>
74inline typename C::const_iterator max_element(const C &c) {
75 return max_element(c.begin(), c.end());
76}
77template <class C, class Compare>
78inline typename C::const_iterator max_element(const C &c, Compare comp) {
79 return max_element(c.begin(), c.end(), comp);
80}
81
82template <class Iter, class Fn>
83inline Fn for_each(std::pair<Iter, Iter> range, Fn fn) {
84 return std::for_each(range.first, range.second, fn);
85}
86
87template <class Iter>
88Iter begin(std::pair<Iter, Iter> pr) {
89 return pr.first;
90}
91template <class Iter>
92Iter end(std::pair<Iter, Iter> pr) {
93 return pr.second;
94}
95
96} // namespace P4
97
98#endif /* LIB_ALGORITHM_H_ */
TODO: this is not really specific to BMV2, it should reside somewhere else.
Definition applyOptionsPragmas.cpp:24