354 lines
9.9 KiB
C++
354 lines
9.9 KiB
C++
#pragma once
|
|
|
|
#include <Void/Memory/Resource.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <cassert>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <expected>
|
|
#include <limits>
|
|
#include <memory>
|
|
#include <memory_resource>
|
|
#include <new>
|
|
#include <utility>
|
|
|
|
namespace Void::Pool
|
|
{
|
|
|
|
enum class PoolError : std::uint8_t
|
|
{
|
|
exhausted,
|
|
allocation_failed,
|
|
invalid_limit
|
|
};
|
|
|
|
struct ObjectPoolLimits
|
|
{
|
|
std::size_t max_live = 4096;
|
|
std::size_t max_total_slots = 4096;
|
|
};
|
|
|
|
// ── ObjectPool<T, ChunkSize> ──────────────────────────────────────────────────
|
|
// Slab-based object pool with stationary shared state so retained smart-pointer
|
|
// leases remain safe if the pool is moved or destroyed before the leases drop.
|
|
// Recycling destroys T and relinks the slot with zero heap allocations.
|
|
|
|
template <typename T, std::size_t ChunkSize = 32>
|
|
requires (ChunkSize >= 1)
|
|
class ObjectPool
|
|
{
|
|
private:
|
|
struct SlabHeader
|
|
{
|
|
SlabHeader* next{nullptr};
|
|
std::size_t slot_count{0};
|
|
std::size_t alloc_bytes{0};
|
|
};
|
|
|
|
union Slot
|
|
{
|
|
alignas(alignof(T)) std::byte storage[sizeof(T)];
|
|
Slot* next;
|
|
};
|
|
|
|
static constexpr std::size_t kSlotAlign = alignof(Slot);
|
|
static constexpr std::size_t kSlabAlign =
|
|
(alignof(SlabHeader) > kSlotAlign) ? alignof(SlabHeader) : kSlotAlign;
|
|
static constexpr std::size_t kHeaderStride =
|
|
((sizeof(SlabHeader) + kSlotAlign - 1) / kSlotAlign) * kSlotAlign;
|
|
|
|
struct State
|
|
{
|
|
std::pmr::memory_resource* upstream;
|
|
ObjectPoolLimits limits;
|
|
SlabHeader* slabs{nullptr};
|
|
Slot* free_head{nullptr};
|
|
std::size_t total_slots{0};
|
|
std::size_t free_count{0};
|
|
std::size_t live{0};
|
|
std::size_t allocated_bytes{0};
|
|
|
|
State(std::pmr::memory_resource* res, ObjectPoolLimits lim) noexcept
|
|
: upstream{res ? res : std::pmr::get_default_resource()},
|
|
limits{lim}
|
|
{
|
|
}
|
|
|
|
~State()
|
|
{
|
|
SlabHeader* cur = slabs;
|
|
while (cur) {
|
|
SlabHeader* next = cur->next;
|
|
const std::size_t bytes = cur->alloc_bytes;
|
|
std::destroy_at(cur);
|
|
upstream->deallocate(cur, bytes, kSlabAlign);
|
|
cur = next;
|
|
}
|
|
slabs = nullptr;
|
|
free_head = nullptr;
|
|
}
|
|
|
|
void push_free(Slot* s) noexcept
|
|
{
|
|
s->next = free_head;
|
|
free_head = s;
|
|
++free_count;
|
|
}
|
|
|
|
void release(T* p) noexcept
|
|
{
|
|
std::destroy_at(p);
|
|
auto* s = reinterpret_cast<Slot*>(p);
|
|
push_free(s);
|
|
--live;
|
|
}
|
|
|
|
Slot* allocate_slab(std::size_t count) noexcept
|
|
{
|
|
constexpr std::size_t kMaxSize = std::numeric_limits<std::size_t>::max();
|
|
if (count == 0 || count > (kMaxSize - kHeaderStride) / sizeof(Slot)) {
|
|
return nullptr;
|
|
}
|
|
const std::size_t bytes = kHeaderStride + count * sizeof(Slot);
|
|
void* raw = nullptr;
|
|
try {
|
|
raw = upstream->allocate(bytes, kSlabAlign);
|
|
} catch (...) {
|
|
return nullptr;
|
|
}
|
|
if (!raw) {
|
|
return nullptr;
|
|
}
|
|
auto* header = std::construct_at(static_cast<SlabHeader*>(raw));
|
|
header->next = slabs;
|
|
header->slot_count = count;
|
|
header->alloc_bytes = bytes;
|
|
slabs = header;
|
|
total_slots += count;
|
|
allocated_bytes += bytes;
|
|
|
|
auto* slots = reinterpret_cast<Slot*>(
|
|
static_cast<std::byte*>(raw) + kHeaderStride);
|
|
for (std::size_t i = count; i > 1; --i) {
|
|
push_free(&slots[i - 1]);
|
|
}
|
|
return &slots[0];
|
|
}
|
|
};
|
|
|
|
public:
|
|
ObjectPool()
|
|
: ObjectPool(ObjectPoolLimits{}, std::pmr::get_default_resource())
|
|
{
|
|
}
|
|
|
|
explicit ObjectPool(
|
|
ObjectPoolLimits limits,
|
|
std::pmr::memory_resource* upstream = std::pmr::get_default_resource())
|
|
: state_{std::make_shared<State>(upstream, limits)}
|
|
{
|
|
}
|
|
|
|
explicit ObjectPool(
|
|
Void::Memory::UnlimitedTag,
|
|
std::pmr::memory_resource* upstream = std::pmr::get_default_resource())
|
|
: state_{std::make_shared<State>(
|
|
upstream,
|
|
ObjectPoolLimits{
|
|
.max_live = std::numeric_limits<std::size_t>::max(),
|
|
.max_total_slots = std::numeric_limits<std::size_t>::max()})}
|
|
{
|
|
}
|
|
|
|
explicit ObjectPool(
|
|
std::pmr::memory_resource* upstream,
|
|
ObjectPoolLimits limits = {})
|
|
: state_{std::make_shared<State>(upstream, limits)}
|
|
{
|
|
}
|
|
|
|
ObjectPool(const ObjectPool&) = delete;
|
|
ObjectPool& operator=(const ObjectPool&) = delete;
|
|
ObjectPool(ObjectPool&&) noexcept = default;
|
|
ObjectPool& operator=(ObjectPool&&) noexcept = default;
|
|
~ObjectPool() = default;
|
|
|
|
struct Deleter
|
|
{
|
|
std::shared_ptr<State> state{};
|
|
void operator()(T* p) const noexcept
|
|
{
|
|
if (p && state) {
|
|
state->release(p);
|
|
}
|
|
}
|
|
};
|
|
|
|
using Ptr = std::unique_ptr<T, Deleter>;
|
|
|
|
template <typename... Args>
|
|
[[nodiscard]] std::expected<Ptr, PoolError> try_acquire(Args&&... args)
|
|
{
|
|
if (!state_) {
|
|
return std::unexpected{PoolError::exhausted};
|
|
}
|
|
if (state_->live >= state_->limits.max_live) {
|
|
return std::unexpected{PoolError::exhausted};
|
|
}
|
|
|
|
Slot* slot = state_->free_head;
|
|
if (slot) {
|
|
state_->free_head = slot->next;
|
|
--state_->free_count;
|
|
} else {
|
|
if (state_->total_slots >= state_->limits.max_total_slots) {
|
|
return std::unexpected{PoolError::exhausted};
|
|
}
|
|
const std::size_t remaining_slots =
|
|
state_->limits.max_total_slots - state_->total_slots;
|
|
const std::size_t batch = std::min(ChunkSize, remaining_slots);
|
|
slot = state_->allocate_slab(batch);
|
|
if (!slot) {
|
|
return std::unexpected{PoolError::allocation_failed};
|
|
}
|
|
}
|
|
|
|
T* obj = reinterpret_cast<T*>(slot);
|
|
try {
|
|
std::construct_at(obj, std::forward<Args>(args)...);
|
|
} catch (...) {
|
|
state_->push_free(slot);
|
|
throw;
|
|
}
|
|
++state_->live;
|
|
return Ptr{obj, Deleter{state_}};
|
|
}
|
|
|
|
template <typename... Args>
|
|
[[nodiscard]] Ptr acquire(Args&&... args)
|
|
{
|
|
auto r = try_acquire(std::forward<Args>(args)...);
|
|
if (!r) {
|
|
throw std::bad_alloc{};
|
|
}
|
|
return std::move(*r);
|
|
}
|
|
|
|
[[nodiscard]] std::size_t capacity() const noexcept
|
|
{
|
|
return state_ ? state_->total_slots : 0;
|
|
}
|
|
|
|
[[nodiscard]] std::size_t available() const noexcept
|
|
{
|
|
return state_ ? state_->free_count : 0;
|
|
}
|
|
|
|
[[nodiscard]] std::size_t live() const noexcept
|
|
{
|
|
return state_ ? state_->live : 0;
|
|
}
|
|
|
|
[[nodiscard]] std::size_t allocated_bytes() const noexcept
|
|
{
|
|
return state_ ? state_->allocated_bytes : 0;
|
|
}
|
|
|
|
[[nodiscard]] ObjectPoolLimits limits() const noexcept
|
|
{
|
|
return state_ ? state_->limits : ObjectPoolLimits{};
|
|
}
|
|
|
|
private:
|
|
std::shared_ptr<State> state_;
|
|
};
|
|
|
|
// ── FixedPool<T, N> ───────────────────────────────────────────────────────────
|
|
// Fixed-capacity pool allocated in-place (no heap after construction).
|
|
|
|
template <typename T, std::size_t N>
|
|
class FixedPool
|
|
{
|
|
public:
|
|
FixedPool() noexcept
|
|
{
|
|
for (std::size_t i = 0; i < N; ++i) {
|
|
free_[i] = slot_ptr(i);
|
|
}
|
|
free_count_ = N;
|
|
}
|
|
|
|
FixedPool(const FixedPool&) = delete;
|
|
FixedPool& operator=(const FixedPool&) = delete;
|
|
|
|
struct Deleter
|
|
{
|
|
FixedPool* pool;
|
|
void operator()(T* p) const noexcept { pool->release(p); }
|
|
};
|
|
|
|
using Ptr = std::unique_ptr<T, Deleter>;
|
|
|
|
template <typename... Args>
|
|
[[nodiscard]] std::expected<Ptr, PoolError>
|
|
try_acquire(Args&&... args) noexcept(std::is_nothrow_constructible_v<T, Args...>)
|
|
{
|
|
if (free_count_ == 0) {
|
|
return std::unexpected{PoolError::exhausted};
|
|
}
|
|
T* slot = free_[--free_count_];
|
|
if constexpr (std::is_nothrow_constructible_v<T, Args...>) {
|
|
std::construct_at(slot, std::forward<Args>(args)...);
|
|
} else {
|
|
try {
|
|
std::construct_at(slot, std::forward<Args>(args)...);
|
|
} catch (...) {
|
|
free_[free_count_++] = slot;
|
|
throw;
|
|
}
|
|
}
|
|
return Ptr{slot, Deleter{this}};
|
|
}
|
|
|
|
template <typename... Args>
|
|
[[nodiscard]] Ptr acquire(Args&&... args) noexcept(
|
|
std::is_nothrow_constructible_v<T, Args...>)
|
|
{
|
|
auto r = try_acquire(std::forward<Args>(args)...);
|
|
if (!r) {
|
|
return nullptr;
|
|
}
|
|
return std::move(*r);
|
|
}
|
|
|
|
[[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; }
|
|
[[nodiscard]] std::size_t available() const noexcept { return free_count_; }
|
|
[[nodiscard]] std::size_t live() const noexcept { return N - free_count_; }
|
|
|
|
private:
|
|
void release(T* p) noexcept
|
|
{
|
|
std::destroy_at(p);
|
|
free_[free_count_++] = p;
|
|
}
|
|
|
|
T* slot_ptr(std::size_t i) noexcept
|
|
{
|
|
return reinterpret_cast<T*>(&storage_[i]);
|
|
}
|
|
|
|
struct alignas(alignof(T)) Slot
|
|
{
|
|
std::byte storage[sizeof(T)];
|
|
};
|
|
|
|
static constexpr std::size_t kStorageCount = (N == 0) ? 1 : N;
|
|
std::array<Slot, kStorageCount> storage_{};
|
|
std::array<T*, kStorageCount> free_{};
|
|
std::size_t free_count_{0};
|
|
};
|
|
|
|
} // namespace Void::Pool
|