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