2020-01-18 08:38:21 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
|
|
|
|
*
|
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 {
|
|
|
|
|
2021-08-30 11:50:01 +00:00
|
|
|
// This class manages a pool of random ID's in the range 1..INT32_MAX
|
2020-01-04 23:28:42 +00:00
|
|
|
class IDAllocator {
|
|
|
|
|
|
|
|
public:
|
2021-01-10 23:29:28 +00:00
|
|
|
IDAllocator() = default;
|
|
|
|
~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()));
|
|
|
|
if (id == 0)
|
|
|
|
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;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
using AK::IDAllocator;
|