bmv2
Designing your own switch target with bmv2
ras.h
1 /* Copyright 2013-present Barefoot Networks, Inc.
2  * Copyright 2021 VMware, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 /*
18  * Antonin Bas (antonin@barefootnetworks.com)
19  *
20  */
21 
22 #ifndef BM_BM_SIM_RAS_H_
23 #define BM_BM_SIM_RAS_H_
24 
25 #include <bm/config.h>
26 
27 #include <algorithm> // for std::swap
28 #include <utility>
29 
30 #include <cassert>
31 
32 #include <boost/container/flat_set.hpp>
33 
34 namespace bm {
35 
36 class RandAccessUIntSet {
37  public:
38  using mbr_t = uintptr_t;
39  using container = boost::container::flat_set<mbr_t>;
40  using iterator = container::iterator;
41  using const_iterator = container::const_iterator;
42 
43  RandAccessUIntSet() = default;
44 
45  RandAccessUIntSet(const RandAccessUIntSet &other) = delete;
46  RandAccessUIntSet &operator=(const RandAccessUIntSet &other) = delete;
47 
48  RandAccessUIntSet(RandAccessUIntSet &&other) = default;
49  RandAccessUIntSet &operator=(RandAccessUIntSet &&other) = default;
50 
51  // returns 0 if already present (0 element added), 1 otherwise
52  int add(mbr_t mbr) {
53  auto p = members.insert(mbr);
54  return p.second ? 1 : 0;
55  }
56 
57  // returns 0 if not present (0 element removed), 1 otherwise
58  int remove(mbr_t mbr) {
59  auto c = members.erase(mbr);
60  return static_cast<int>(c);
61  }
62 
63  bool contains(mbr_t mbr) const {
64  return members.find(mbr) != members.end();
65  }
66 
67  size_t count() const {
68  return members.size();
69  }
70 
71  // n >= 0, 0 is first element in set
72  mbr_t get_nth(size_t n) const {
73  auto it = members.nth(n);
74  return *it;
75  }
76 
77  iterator begin() {
78  return members.begin();
79  }
80 
81  const_iterator begin() const {
82  return members.begin();
83  }
84 
85  iterator end() {
86  return members.end();
87  }
88 
89  const_iterator end() const {
90  return members.end();
91  }
92 
93  private:
94  container members;
95 };
96 
97 } // namespace bm
98 
99 #endif // BM_BM_SIM_RAS_H_