id_generator.h 1.2 KB

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