1 /* 2 * Copyright 2019 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 #pragma once 18 19 #include <array> 20 21 /* Helper class generating N unique ids, from 0 to N-1 */ 22 template <std::size_t N> 23 class IdGenerator { 24 public: 25 static int ALL_USED; 26 IdGenerator()27 IdGenerator() : in_use_{} {} 28 29 /* Returns next free id, or ALL_USED if no ids left */ GetNext()30 int GetNext() { 31 for (std::size_t i = 0; i < N; i++) { 32 if (!in_use_[i]) { 33 in_use_[i] = true; 34 return i; 35 } 36 } 37 return ALL_USED; 38 } 39 40 /* Release given ID */ Release(int id)41 void Release(int id) { in_use_[id] = false; } 42 43 private: 44 std::array<bool, N> in_use_; 45 }; 46 47 template <std::size_t N> 48 int IdGenerator<N>::ALL_USED = -1;