feat(Containers): fix pool lease lifetimes/budgets and non-spinning MPSC ring (M-CONTAINERS-02, M-CONTAINERS-03)
This commit is contained in:
1 parent
883bbdcf38
commit
9ac76bbcf9
7 files changed
+1252
-285
No files matched your search
@@ -1,109 +1,272 @@
|
||||
#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>
|
||||
#include <vector>
|
||||
|
||||
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> ──────────────────────────────────────────────────
|
||||
// A slab-based object pool. acquire() returns a unique_ptr<T> with a custom
|
||||
// deleter that returns the object to the pool instead of freeing memory.
|
||||
// Objects are constructed in-place; the pool owns the backing storage.
|
||||
//
|
||||
// Thread-safety: NOT thread-safe. Add external synchronisation if needed.
|
||||
// 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() = default;
|
||||
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&&) = default;
|
||||
ObjectPool& operator=(ObjectPool&&) = default;
|
||||
|
||||
ObjectPool(ObjectPool&&) noexcept = default;
|
||||
ObjectPool& operator=(ObjectPool&&) noexcept = default;
|
||||
~ObjectPool() = default;
|
||||
|
||||
struct Deleter
|
||||
{
|
||||
ObjectPool* pool;
|
||||
void operator()(T* p) const noexcept { pool->release(p); }
|
||||
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)
|
||||
{
|
||||
T* slot = pop_free();
|
||||
if (!slot) {
|
||||
slot = allocate_slot();
|
||||
auto r = try_acquire(std::forward<Args>(args)...);
|
||||
if (!r) {
|
||||
throw std::bad_alloc{};
|
||||
}
|
||||
std::construct_at(slot, std::forward<Args>(args)...);
|
||||
return Ptr{slot, Deleter{this}};
|
||||
return std::move(*r);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t capacity() const noexcept
|
||||
{
|
||||
return slabs_.size() * ChunkSize;
|
||||
return state_ ? state_->total_slots : 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t available() const noexcept
|
||||
{
|
||||
return free_.size();
|
||||
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:
|
||||
void release(T* p) noexcept
|
||||
{
|
||||
std::destroy_at(p);
|
||||
free_.push_back(p);
|
||||
}
|
||||
|
||||
T* pop_free() noexcept
|
||||
{
|
||||
if (free_.empty()) return nullptr;
|
||||
T* p = free_.back();
|
||||
free_.pop_back();
|
||||
return p;
|
||||
}
|
||||
|
||||
T* allocate_slot()
|
||||
{
|
||||
// Grow by one slab; keep all subsequent objects from the same slab
|
||||
// available in free_.
|
||||
auto& slab = slabs_.emplace_back();
|
||||
slab = std::make_unique<Slab>();
|
||||
// Push all but the first slot into free_.
|
||||
for (std::size_t i = 1; i < ChunkSize; ++i) {
|
||||
free_.push_back(reinterpret_cast<T*>(&slab->storage[i]));
|
||||
}
|
||||
return reinterpret_cast<T*>(&slab->storage[0]);
|
||||
}
|
||||
|
||||
struct alignas(alignof(T)) Slot
|
||||
{
|
||||
std::byte storage[sizeof(T)];
|
||||
};
|
||||
|
||||
struct Slab
|
||||
{
|
||||
Slot storage[ChunkSize];
|
||||
};
|
||||
|
||||
std::vector<std::unique_ptr<Slab>> slabs_;
|
||||
std::vector<T*> free_;
|
||||
std::shared_ptr<State> state_;
|
||||
};
|
||||
|
||||
// ── FixedPool<T, N> ───────────────────────────────────────────────────────────
|
||||
// A fixed-capacity pool allocated in-place (no heap after construction).
|
||||
// Capacity is known at compile time; acquire() returns nullptr when full.
|
||||
// Fixed-capacity pool allocated in-place (no heap after construction).
|
||||
|
||||
template <typename T, std::size_t N>
|
||||
class FixedPool
|
||||
@@ -128,18 +291,41 @@ public:
|
||||
|
||||
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...>)
|
||||
{
|
||||
if (free_count_ == 0) return nullptr;
|
||||
T* slot = free_[--free_count_];
|
||||
std::construct_at(slot, std::forward<Args>(args)...);
|
||||
return Ptr{slot, Deleter{this}};
|
||||
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
|
||||
@@ -158,8 +344,9 @@ private:
|
||||
std::byte storage[sizeof(T)];
|
||||
};
|
||||
|
||||
Slot storage_[N];
|
||||
T* free_[N];
|
||||
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};
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user