1 // Copyright 2017 The Fuchsia Authors
2 //
3 // Use of this source code is governed by a MIT-style
4 // license that can be found in the LICENSE file or at
5 // https://opensource.org/licenses/MIT
6 
7 #pragma once
8 
9 #include <bitmap/raw-bitmap.h>
10 #include <bitmap/storage.h>
11 
12 namespace hypervisor {
13 
14 // Allocates architecture-specific resource IDs.
15 //
16 // |T| is the type of the ID, and is an integral type.
17 // |N| is the maximum value of an ID.
18 template <typename T, T N>
19 class IdAllocator {
20 public:
Init()21     zx_status_t Init() {
22         return id_bitmap_.Reset(N);
23     }
24 
AllocId(T * id)25     zx_status_t AllocId(T* id) {
26         size_t first_unset;
27         bool all_set = id_bitmap_.Get(0, N, &first_unset);
28         if (all_set)
29             return ZX_ERR_NO_RESOURCES;
30         if (first_unset >= N)
31             return ZX_ERR_OUT_OF_RANGE;
32         *id = static_cast<T>(first_unset + 1);
33         return id_bitmap_.SetOne(first_unset);
34     }
35 
FreeId(T id)36     zx_status_t FreeId(T id) {
37         if (id == 0 || !id_bitmap_.GetOne(id - 1))
38             return ZX_ERR_INVALID_ARGS;
39         return id_bitmap_.ClearOne(id - 1);
40     }
41 
42 private:
43     bitmap::RawBitmapGeneric<bitmap::FixedStorage<N>> id_bitmap_;
44 };
45 
46 } // namespace hypervisor
47