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