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 #include "src/tracing/core/id_allocator.h" 18 19 #include "perfetto/base/logging.h" 20 21 namespace perfetto { 22 IdAllocatorGeneric(uint32_t max_id)23IdAllocatorGeneric::IdAllocatorGeneric(uint32_t max_id) : max_id_(max_id) { 24 PERFETTO_DCHECK(max_id > 1); 25 } 26 27 IdAllocatorGeneric::~IdAllocatorGeneric() = default; 28 AllocateGeneric()29uint32_t IdAllocatorGeneric::AllocateGeneric() { 30 for (uint32_t ignored = 1; ignored <= max_id_; ignored++) { 31 last_id_ = last_id_ < max_id_ ? last_id_ + 1 : 1; 32 const auto id = last_id_; 33 34 // 0 is never a valid ID. So if we are looking for |id| == N and there are 35 // N or less elements in the vector, they must necessarily be all < N. 36 // e.g. if |id| == 4 and size() == 4, the vector will contain IDs 0,1,2,3. 37 if (id >= ids_.size()) { 38 ids_.resize(id + 1); 39 ids_[id] = true; 40 return id; 41 } 42 43 if (!ids_[id]) { 44 ids_[id] = true; 45 return id; 46 } 47 } 48 return 0; 49 } 50 FreeGeneric(uint32_t id)51void IdAllocatorGeneric::FreeGeneric(uint32_t id) { 52 if (id == 0 || id >= ids_.size() || !ids_[id]) { 53 PERFETTO_DFATAL("Invalid id."); 54 return; 55 } 56 ids_[id] = false; 57 } 58 59 } // namespace perfetto 60