• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
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 #ifndef INCLUDE_PERFETTO_EXT_BASE_SMALL_SET_H_
18 #define INCLUDE_PERFETTO_EXT_BASE_SMALL_SET_H_
19 
20 #include <array>
21 #include <cstdlib>
22 
23 namespace perfetto {
24 
25 // Set that can store up to Size items of DataType.
26 // Lookup is O(Size), so it is only usable for very small sets.
27 template <typename DataType, size_t Size>
28 class SmallSet {
29   static_assert(Size < 16, "Do not use SmallSet for many items");
30 
31  public:
32   // Name for consistency with STL.
33   using const_iterator = typename std::array<DataType, Size>::const_iterator;
Add(DataType n)34   bool Add(DataType n) {
35     if (Contains(n))
36       return true;
37     if (filled_ < Size) {
38       arr_[filled_++] = std::move(n);
39       return true;
40     }
41     return false;
42   }
43 
Contains(const DataType & n)44   bool Contains(const DataType& n) const {
45     for (size_t i = 0; i < filled_; ++i) {
46       if (arr_[i] == n)
47         return true;
48     }
49     return false;
50   }
51 
begin()52   const_iterator begin() const { return arr_.cbegin(); }
end()53   const_iterator end() const {
54     return arr_.cbegin() + static_cast<ssize_t>(filled_);
55   }
size()56   size_t size() const { return filled_; }
57 
58  private:
59   std::array<DataType, Size> arr_;
60   size_t filled_ = 0;
61 };
62 
63 }  // namespace perfetto
64 
65 #endif  // INCLUDE_PERFETTO_EXT_BASE_SMALL_SET_H_
66