2020-01-18 08:38:21 +00:00
|
|
|
/*
|
2024-10-04 11:19:50 +00:00
|
|
|
* Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>
|
2020-01-18 08:38:21 +00:00
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-01-18 08:38:21 +00:00
|
|
|
*/
|
|
|
|
|
2020-01-04 23:28:42 +00:00
|
|
|
#pragma once
|
|
|
|
|
2021-03-12 16:29:37 +00:00
|
|
|
#include <AK/Forward.h>
|
2020-01-04 23:28:42 +00:00
|
|
|
#include <AK/HashTable.h>
|
2021-08-30 11:50:01 +00:00
|
|
|
#include <AK/Random.h>
|
2020-01-04 23:28:42 +00:00
|
|
|
|
|
|
|
namespace AK {
|
|
|
|
|
2023-04-06 11:29:05 +00:00
|
|
|
// This class manages a pool of random ID's in the range N (default of 1) to INT32_MAX
|
2020-01-04 23:28:42 +00:00
|
|
|
class IDAllocator {
|
|
|
|
|
|
|
|
public:
|
2021-01-10 23:29:28 +00:00
|
|
|
IDAllocator() = default;
|
2023-04-06 11:29:05 +00:00
|
|
|
|
|
|
|
explicit IDAllocator(int minimum_value)
|
|
|
|
: m_minimum_value(minimum_value)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2021-01-10 23:29:28 +00:00
|
|
|
~IDAllocator() = default;
|
2020-01-04 23:28:42 +00:00
|
|
|
|
|
|
|
int allocate()
|
|
|
|
{
|
2021-08-30 11:50:01 +00:00
|
|
|
VERIFY(m_allocated_ids.size() < (INT32_MAX - 2));
|
|
|
|
int id = 0;
|
|
|
|
for (;;) {
|
|
|
|
id = static_cast<int>(get_random_uniform(NumericLimits<int>::max()));
|
2023-04-06 11:29:05 +00:00
|
|
|
if (id < m_minimum_value)
|
2021-08-30 11:50:01 +00:00
|
|
|
continue;
|
|
|
|
if (m_allocated_ids.set(id) == AK::HashSetResult::InsertedNewEntry)
|
|
|
|
break;
|
2020-01-04 23:28:42 +00:00
|
|
|
}
|
2021-08-30 11:50:01 +00:00
|
|
|
return id;
|
2020-01-04 23:28:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void deallocate(int id)
|
|
|
|
{
|
|
|
|
m_allocated_ids.remove(id);
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
HashTable<int> m_allocated_ids;
|
2023-04-06 11:29:05 +00:00
|
|
|
int m_minimum_value { 1 };
|
2020-01-04 23:28:42 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-11-26 11:18:30 +00:00
|
|
|
#if USING_AK_GLOBALLY
|
2020-01-04 23:28:42 +00:00
|
|
|
using AK::IDAllocator;
|
2022-11-26 11:18:30 +00:00
|
|
|
#endif
|