Coverage Report

Created: 2026-09-26 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/AK/IDAllocator.h
Line
Count
Source
1
/*
2
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3
 *
4
 * SPDX-License-Identifier: BSD-2-Clause
5
 */
6
7
#pragma once
8
9
#include <AK/Forward.h>
10
#include <AK/HashTable.h>
11
#include <AK/Random.h>
12
13
namespace AK {
14
15
// This class manages a pool of random ID's in the range N (default of 1) to INT32_MAX
16
class IDAllocator {
17
18
public:
19
0
    IDAllocator() = default;
20
21
    explicit IDAllocator(int minimum_value)
22
0
        : m_minimum_value(minimum_value)
23
0
    {
24
0
    }
25
26
0
    ~IDAllocator() = default;
27
28
    int allocate()
29
0
    {
30
0
        VERIFY(m_allocated_ids.size() < (INT32_MAX - 2));
31
0
        int id = 0;
32
0
        for (;;) {
33
0
            id = static_cast<int>(get_random_uniform(NumericLimits<int>::max()));
34
0
            if (id < m_minimum_value)
35
0
                continue;
36
0
            if (m_allocated_ids.set(id) == AK::HashSetResult::InsertedNewEntry)
37
0
                break;
38
0
        }
39
0
        return id;
40
0
    }
41
42
    void deallocate(int id)
43
0
    {
44
0
        m_allocated_ids.remove(id);
45
0
    }
46
47
private:
48
    HashTable<int> m_allocated_ids;
49
    int m_minimum_value { 1 };
50
};
51
}
52
53
#if USING_AK_GLOBALLY
54
using AK::IDAllocator;
55
#endif