1 /* 2 * Copyright (C) 2017 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 SRC_TRACING_CORE_ID_ALLOCATOR_H_ 18 #define SRC_TRACING_CORE_ID_ALLOCATOR_H_ 19 20 #include <stdint.h> 21 22 #include <type_traits> 23 #include <vector> 24 25 namespace perfetto { 26 27 // Handles assigment of IDs (int types) from a fixed-size pool. 28 // Zero is not considered a valid ID. 29 // The base class takes always a uint32_t and the derived class casts and checks 30 // bounds at compile time. This is to avoid bloating code with different 31 // instances of the main class for each size. 32 class IdAllocatorGeneric { 33 public: 34 // |max_id| is inclusive. 35 explicit IdAllocatorGeneric(uint32_t max_id); 36 ~IdAllocatorGeneric(); 37 38 // Returns an ID in the range [1, max_id] or 0 if no more ids are available. 39 uint32_t AllocateGeneric(); 40 void FreeGeneric(uint32_t); 41 42 bool IsEmpty() const; 43 44 private: 45 IdAllocatorGeneric(const IdAllocatorGeneric&) = delete; 46 IdAllocatorGeneric& operator=(const IdAllocatorGeneric&) = delete; 47 48 const uint32_t max_id_; 49 uint32_t last_id_ = 0; 50 std::vector<bool> ids_; 51 }; 52 53 template <typename T = uint32_t> 54 class IdAllocator : public IdAllocatorGeneric { 55 public: IdAllocator(T end)56 explicit IdAllocator(T end) : IdAllocatorGeneric(end) { 57 static_assert(std::is_integral<T>::value && std::is_unsigned<T>::value, 58 "T must be an unsigned integer"); 59 static_assert(sizeof(T) <= sizeof(uint32_t), "T is too big"); 60 } 61 Allocate()62 T Allocate() { return static_cast<T>(AllocateGeneric()); } Free(T id)63 void Free(T id) { FreeGeneric(id); } 64 }; 65 66 } // namespace perfetto 67 68 #endif // SRC_TRACING_CORE_ID_ALLOCATOR_H_ 69