feat(Containers): fix pool lease lifetimes/budgets and non-spinning MPSC ring (M-CONTAINERS-02, M-CONTAINERS-03)

This commit is contained in:
faumaray committed 2026-11-24 03:20:04 +03:00
1 parent 883bbdcf38
commit 9ac76bbcf9
7 files changed
+1252 -285

No files matched your search

+362 -164
View File
@@ -1,203 +1,401 @@
#pragma once
#include <Void/Memory/Resource.hpp>
#include <algorithm>
#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <limits>
#include <memory>
#include <memory_resource>
#include <new>
#include <span>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::BufferPool
{
// ── BufferPool<T>
// ───────────────────────────────────────────────────────────── A pool of
// reusable, variable-length buffers of T — e.g. audio sample blocks (int16
// / float). Distinct from Containers/Pool.hpp's ObjectPool, which pools
// fixed-size *objects*: this pools backing storage sized by request.
//
// acquire(n) hands back a Buffer of logical length n backed by capacity
// rounded up to the next power-of-two size class; on drop the storage
// returns to the pool's bucket for that size class, so a later acquire of
// the same class reuses it with no reallocation.
//
// Not thread-safe — guard externally if shared.
enum class BufferPoolError : std::uint8_t
{
request_too_large,
budget_exceeded,
allocation_failed,
size_overflow
};
template <typename T> class BufferPool
{
public:
// ── BufferPool<T> ─────────────────────────────────────────────────────────────
// A pool of reusable, variable-length buffers of T with stationary shared state,
// O(1) power-of-two bucket lists, explicit PMR upstream resource support, and
// bounded request/idle/total byte limits.
BufferPool() = default;
template <typename T> class BufferPool
{
public:
struct Limits
{
std::size_t max_request_bytes = 1024 * 1024;
std::size_t max_idle_bytes = 16 * 1024 * 1024;
std::size_t max_total_bytes = 64 * 1024 * 1024;
};
BufferPool(const BufferPool&) = delete;
BufferPool& operator=(const BufferPool&) = delete;
BufferPool(BufferPool&&) = default;
BufferPool& operator=(BufferPool&&) = default;
struct Stats
{
std::uint64_t allocations = 0; // fresh storage allocated
std::uint64_t reuses = 0; // requests served from a bucket
std::size_t pooled = 0; // buffers currently idle in buckets
std::size_t idle_bytes = 0;
std::size_t checked_out_bytes = 0;
std::size_t total_bytes = 0;
std::uint64_t dropped_on_return = 0; // released directly to upstream
};
struct Stats {
std::uint64_t allocations = 0; // fresh storage allocated
std::uint64_t reuses = 0; // requests served from a bucket
std::size_t pooled = 0; // buffers currently idle in buckets
};
private:
struct Node
{
Node* next{nullptr};
std::size_t cls{0};
std::size_t payload_bytes{0};
std::size_t total_alloc_bytes{0};
std::size_t bucket_idx{0};
};
// An owning view returned by acquire(); recycles its storage on
// drop.
class Buffer
{
public:
static constexpr std::size_t kBlockAlign =
(alignof(Node) > alignof(T)) ? alignof(Node) : alignof(T);
static constexpr std::size_t kDataOffset =
((sizeof(Node) + alignof(T) - 1) / alignof(T)) * alignof(T);
static constexpr std::size_t kNumBuckets = 65;
Buffer() = default;
static T* data_ptr(Node* node) noexcept
{
return reinterpret_cast<T*>(
reinterpret_cast<std::byte*>(node) + kDataOffset);
}
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
struct State
{
std::pmr::memory_resource* upstream;
Limits limits;
std::array<Node*, kNumBuckets> buckets{};
std::uint64_t allocations{0};
std::uint64_t reuses{0};
std::size_t pooled{0};
std::size_t idle_bytes{0};
std::size_t checked_out_bytes{0};
std::uint64_t dropped_on_return{0};
bool owner_alive{true};
Buffer(Buffer&& other) noexcept
: pool_{other.pool_},
storage_{std::move(other.storage_)},
size_{other.size_}
{
other.pool_ = nullptr;
other.size_ = 0;
}
State(std::pmr::memory_resource* res, Limits lim) noexcept
: upstream{res ? res : std::pmr::get_default_resource()},
limits{lim}
{
}
Buffer& operator=(Buffer&& other) noexcept
{
if (this != &other) {
recycle();
pool_ = other.pool_;
storage_ = std::move(other.storage_);
size_ = other.size_;
other.pool_ = nullptr;
other.size_ = 0;
}
return *this;
}
~State() { shrink(); }
~Buffer() { recycle(); }
void destroy_node(Node* node) noexcept
{
T* data = data_ptr(node);
std::destroy_n(data, node->cls);
const std::size_t bytes = node->total_alloc_bytes;
std::destroy_at(node);
upstream->deallocate(node, bytes, kBlockAlign);
}
[[nodiscard]] T* data() noexcept { return storage_.data(); }
[[nodiscard]] const T* data() const noexcept
{
return storage_.data();
}
[[nodiscard]] std::size_t size() const noexcept
{
return size_;
}
[[nodiscard]] bool empty() const noexcept
{
return size_ == 0;
}
// Backing capacity (the size class) — always >= size().
[[nodiscard]] std::size_t capacity() const noexcept
{
return storage_.size();
}
void shrink() noexcept
{
for (Node*& head : buckets) {
while (head) {
Node* node = head;
head = node->next;
idle_bytes -= node->payload_bytes;
--pooled;
destroy_node(node);
}
}
}
[[nodiscard]] T& operator[](std::size_t i) noexcept
{
return storage_[i];
}
[[nodiscard]] const T&
operator[](std::size_t i) const noexcept
{
return storage_[i];
}
void release(Node* node) noexcept
{
checked_out_bytes -= node->payload_bytes;
const std::size_t b = node->payload_bytes;
const bool can_retain =
owner_alive &&
b <= limits.max_idle_bytes &&
idle_bytes <= limits.max_idle_bytes - b &&
(checked_out_bytes + idle_bytes) <= limits.max_total_bytes - b;
if (can_retain) {
node->next = buckets[node->bucket_idx];
buckets[node->bucket_idx] = node;
++pooled;
idle_bytes += b;
} else {
destroy_node(node);
++dropped_on_return;
}
}
};
[[nodiscard]] T* begin() noexcept { return data(); }
[[nodiscard]] T* end() noexcept { return data() + size_; }
[[nodiscard]] const T* begin() const noexcept
{
return data();
}
[[nodiscard]] const T* end() const noexcept
{
return data() + size_;
}
public:
BufferPool()
: BufferPool(Limits{}, std::pmr::get_default_resource())
{
}
[[nodiscard]] std::span<T> span() noexcept
{
return {data(), size_};
}
[[nodiscard]] std::span<const T> span() const noexcept
{
return {data(), size_};
}
explicit BufferPool(
Limits limits,
std::pmr::memory_resource* upstream = std::pmr::get_default_resource())
: state_{std::make_shared<State>(upstream, limits)}
{
}
private:
explicit BufferPool(
Void::Memory::UnlimitedTag,
std::pmr::memory_resource* upstream = std::pmr::get_default_resource())
: state_{std::make_shared<State>(
upstream,
Limits{
.max_request_bytes = std::numeric_limits<std::size_t>::max(),
.max_idle_bytes = std::numeric_limits<std::size_t>::max(),
.max_total_bytes = std::numeric_limits<std::size_t>::max()})}
{
}
friend class BufferPool;
explicit BufferPool(
std::pmr::memory_resource* upstream,
Limits limits = {})
: state_{std::make_shared<State>(upstream, limits)}
{
}
Buffer(BufferPool* pool, std::vector<T> storage,
std::size_t n) noexcept
: pool_{pool}, storage_{std::move(storage)}, size_{n}
{
}
BufferPool(const BufferPool&) = delete;
BufferPool& operator=(const BufferPool&) = delete;
void recycle() noexcept
{
if (pool_) {
pool_->recycle(std::move(storage_));
pool_ = nullptr;
}
}
BufferPool(BufferPool&&) noexcept = default;
BufferPool* pool_ = nullptr;
std::vector<T> storage_;
std::size_t size_ = 0;
};
BufferPool& operator=(BufferPool&& other) noexcept
{
if (this != &other) {
teardown();
state_ = std::move(other.state_);
}
return *this;
}
// Hand out a buffer of logical length n (capacity rounded up to a
// power of two), reusing pooled storage of that size class when
// available.
[[nodiscard]] Buffer acquire(std::size_t n)
{
const std::size_t cls = size_class(n);
std::vector<T> storage;
auto bucket = free_.find(cls);
if (bucket != free_.end() && !bucket->second.empty()) {
storage = std::move(bucket->second.back());
bucket->second.pop_back();
++reuses_;
} else {
storage.resize(cls);
++allocations_;
}
return Buffer{this, std::move(storage), n};
}
~BufferPool() { teardown(); }
[[nodiscard]] Stats stats() const
{
std::size_t pooled = 0;
for (const auto& [cls, bucket] : free_) {
pooled += bucket.size();
}
return Stats{allocations_, reuses_, pooled};
}
// Owning view returned by acquire()/try_acquire(); recycles cleanly on drop.
class Buffer
{
public:
Buffer() = default;
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
// Drop all pooled (idle) storage. Outstanding Buffers are
// unaffected.
void shrink() noexcept { free_.clear(); }
Buffer(Buffer&& other) noexcept
: state_{std::move(other.state_)},
node_{std::exchange(other.node_, nullptr)},
size_{std::exchange(other.size_, 0)}
{
}
private:
Buffer& operator=(Buffer&& other) noexcept
{
if (this != &other) {
recycle();
state_ = std::move(other.state_);
node_ = std::exchange(other.node_, nullptr);
size_ = std::exchange(other.size_, 0);
}
return *this;
}
static std::size_t size_class(std::size_t n) noexcept
{
return n == 0 ? 0 : std::bit_ceil(n);
}
~Buffer() { recycle(); }
void recycle(std::vector<T> storage)
{
if (storage.empty()) {
return;
}
free_[storage.size()].push_back(std::move(storage));
}
[[nodiscard]] T* data() noexcept
{
return node_ ? data_ptr(node_) : nullptr;
}
[[nodiscard]] const T* data() const noexcept
{
return node_ ? data_ptr(node_) : nullptr;
}
[[nodiscard]] std::size_t size() const noexcept { return size_; }
[[nodiscard]] bool empty() const noexcept { return size_ == 0; }
[[nodiscard]] std::size_t capacity() const noexcept
{
return node_ ? node_->cls : 0;
}
std::unordered_map<std::size_t, std::vector<std::vector<T>>> free_;
std::uint64_t allocations_ = 0;
std::uint64_t reuses_ = 0;
};
[[nodiscard]] T& operator[](std::size_t i) noexcept { return data()[i]; }
[[nodiscard]] const T& operator[](std::size_t i) const noexcept
{
return data()[i];
}
[[nodiscard]] T* begin() noexcept { return data(); }
[[nodiscard]] T* end() noexcept { return data() ? data() + size_ : nullptr; }
[[nodiscard]] const T* begin() const noexcept { return data(); }
[[nodiscard]] const T* end() const noexcept
{
return data() ? data() + size_ : nullptr;
}
[[nodiscard]] std::span<T> span() noexcept { return {data(), size_}; }
[[nodiscard]] std::span<const T> span() const noexcept
{
return {data(), size_};
}
private:
friend class BufferPool;
Buffer(std::shared_ptr<State> state, Node* node, std::size_t n) noexcept
: state_{std::move(state)}, node_{node}, size_{n}
{
}
void recycle() noexcept
{
if (node_ && state_) {
state_->release(node_);
}
node_ = nullptr;
size_ = 0;
state_.reset();
}
std::shared_ptr<State> state_{};
Node* node_{nullptr};
std::size_t size_{0};
};
[[nodiscard]] std::expected<Buffer, BufferPoolError>
try_acquire(std::size_t n)
{
if (!state_) {
return std::unexpected{BufferPoolError::budget_exceeded};
}
if (n == 0) {
return Buffer{};
}
constexpr std::size_t kMaxSize = std::numeric_limits<std::size_t>::max();
constexpr std::size_t kMaxPow2 =
std::size_t{1} << (std::numeric_limits<std::size_t>::digits - 1);
if (n > kMaxPow2) {
return std::unexpected{BufferPoolError::size_overflow};
}
const std::size_t cls = std::bit_ceil(n);
if (cls > (kMaxSize / sizeof(T))) {
return std::unexpected{BufferPoolError::size_overflow};
}
const std::size_t payload_bytes = cls * sizeof(T);
if (payload_bytes > state_->limits.max_request_bytes) {
return std::unexpected{BufferPoolError::request_too_large};
}
if (payload_bytes > (kMaxSize - kDataOffset)) {
return std::unexpected{BufferPoolError::size_overflow};
}
const std::size_t bucket_idx =
static_cast<std::size_t>(std::countr_zero(cls));
if (Node* reused = state_->buckets[bucket_idx]) {
state_->buckets[bucket_idx] = reused->next;
reused->next = nullptr;
--state_->pooled;
state_->idle_bytes -= reused->payload_bytes;
state_->checked_out_bytes += reused->payload_bytes;
++state_->reuses;
return Buffer{state_, reused, n};
}
const std::size_t active_bytes =
state_->checked_out_bytes + state_->idle_bytes;
if (payload_bytes > state_->limits.max_total_bytes ||
active_bytes > state_->limits.max_total_bytes - payload_bytes) {
return std::unexpected{BufferPoolError::budget_exceeded};
}
const std::size_t total_alloc_bytes = kDataOffset + payload_bytes;
void* raw = nullptr;
try {
raw = state_->upstream->allocate(total_alloc_bytes, kBlockAlign);
} catch (...) {
return std::unexpected{BufferPoolError::allocation_failed};
}
if (!raw) {
return std::unexpected{BufferPoolError::allocation_failed};
}
Node* node = std::construct_at(static_cast<Node*>(raw));
node->cls = cls;
node->payload_bytes = payload_bytes;
node->total_alloc_bytes = total_alloc_bytes;
node->bucket_idx = bucket_idx;
try {
std::uninitialized_value_construct_n(data_ptr(node), cls);
} catch (...) {
std::destroy_at(node);
state_->upstream->deallocate(raw, total_alloc_bytes, kBlockAlign);
throw;
}
state_->checked_out_bytes += payload_bytes;
++state_->allocations;
return Buffer{state_, node, n};
}
[[nodiscard]] Buffer acquire(std::size_t n)
{
auto r = try_acquire(n);
if (!r) {
throw std::bad_alloc{};
}
return std::move(*r);
}
[[nodiscard]] Stats stats() const noexcept
{
if (!state_) {
return Stats{};
}
return Stats{
state_->allocations,
state_->reuses,
state_->pooled,
state_->idle_bytes,
state_->checked_out_bytes,
state_->idle_bytes + state_->checked_out_bytes,
state_->dropped_on_return};
}
[[nodiscard]] Limits limits() const noexcept
{
return state_ ? state_->limits : Limits{};
}
// Drop all pooled (idle) storage. Outstanding Buffers are unaffected.
void shrink() noexcept
{
if (state_) {
state_->shrink();
}
}
private:
void teardown() noexcept
{
if (state_) {
state_->owner_alive = false;
state_->shrink();
}
}
std::shared_ptr<State> state_;
};
} // namespace Void::BufferPool
+253 -66
View File
@@ -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};
};
+237 -54
View File
@@ -3,20 +3,52 @@
#include <atomic>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <new>
#include <optional>
#include <type_traits>
#include <utility>
namespace Void::Ring
{
enum class PushStatus : std::uint8_t
{
ok,
full,
closed
};
enum class PopStatus : std::uint8_t
{
ok,
empty,
pending,
closed
};
template <typename T> struct PopResult
{
PopStatus status{PopStatus::empty};
std::optional<T> value{};
[[nodiscard]] constexpr bool has_value() const noexcept
{
return value.has_value();
}
[[nodiscard]] constexpr explicit operator bool() const noexcept
{
return value.has_value();
}
};
// ── SpscRing<T, N> ────────────────────────────────────────────────────────────
// Single-producer / single-consumer lock-free ring buffer.
// Capacity is N (must be a power of two). The buffer holds at most N-1 items.
// All operations are wait-free.
// Single-producer / single-consumer wait-free bounded ring buffer.
// Capacity is N - 1 usable entries (N must be a power of two).
template <typename T, std::size_t N>
requires(N >= 2 && (N & (N - 1)) == 0) // power of two
requires(N >= 2 && (N & (N - 1)) == 0)
class SpscRing
{
public:
@@ -25,13 +57,89 @@ public:
SpscRing(const SpscRing&) = delete;
SpscRing& operator=(const SpscRing&) = delete;
// Producer side — push returns false when the buffer is full.
~SpscRing()
{
std::size_t t = tail_.load(std::memory_order_acquire);
const std::size_t h = head_.load(std::memory_order_acquire);
while (t != h) {
std::destroy_at(slot_ptr(t));
t = (t + 1) & mask_;
}
}
void close() noexcept { closed_.store(true, std::memory_order_release); }
[[nodiscard]] bool is_closed() const noexcept
{
return closed_.load(std::memory_order_acquire);
}
[[nodiscard]] PushStatus try_push(const T& val)
noexcept(std::is_nothrow_copy_constructible_v<T>)
requires(std::is_nothrow_copy_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
{
if (closed_.load(std::memory_order_acquire)) {
return PushStatus::closed;
}
const std::size_t head = head_.load(std::memory_order_relaxed);
const std::size_t next = (head + 1) & mask_;
if (next == tail_.load(std::memory_order_acquire)) {
return PushStatus::full;
}
std::construct_at(slot_ptr(head), val);
head_.store(next, std::memory_order_release);
return PushStatus::ok;
}
[[nodiscard]] PushStatus try_push(T&& val)
noexcept(std::is_nothrow_move_constructible_v<T>)
requires(std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
{
if (closed_.load(std::memory_order_acquire)) {
return PushStatus::closed;
}
const std::size_t head = head_.load(std::memory_order_relaxed);
const std::size_t next = (head + 1) & mask_;
if (next == tail_.load(std::memory_order_acquire)) {
return PushStatus::full;
}
std::construct_at(slot_ptr(head), std::move(val));
head_.store(next, std::memory_order_release);
return PushStatus::ok;
}
[[nodiscard]] PopResult<T> try_pop() noexcept(
std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
requires(std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
{
const std::size_t tail = tail_.load(std::memory_order_relaxed);
if (tail == head_.load(std::memory_order_acquire)) {
return PopResult<T>{
closed_.load(std::memory_order_acquire) ? PopStatus::closed : PopStatus::empty,
std::nullopt};
}
T val{std::move(*slot_ptr(tail))};
std::destroy_at(slot_ptr(tail));
tail_.store((tail + 1) & mask_, std::memory_order_release);
return PopResult<T>{PopStatus::ok, std::move(val)};
}
// Legacy 1.x producer/consumer methods (compatible with throwing/nothrow types)
[[nodiscard]] bool push(const T& val)
noexcept(std::is_nothrow_copy_constructible_v<T>)
{
if (closed_.load(std::memory_order_acquire)) {
return false;
}
const std::size_t head = head_.load(std::memory_order_relaxed);
const std::size_t next = (head + 1) & mask_;
if (next == tail_.load(std::memory_order_acquire)) return false;
if (next == tail_.load(std::memory_order_acquire)) {
return false;
}
std::construct_at(slot_ptr(head), val);
head_.store(next, std::memory_order_release);
return true;
@@ -40,21 +148,27 @@ public:
[[nodiscard]] bool push(T&& val)
noexcept(std::is_nothrow_move_constructible_v<T>)
{
if (closed_.load(std::memory_order_acquire)) {
return false;
}
const std::size_t head = head_.load(std::memory_order_relaxed);
const std::size_t next = (head + 1) & mask_;
if (next == tail_.load(std::memory_order_acquire)) return false;
if (next == tail_.load(std::memory_order_acquire)) {
return false;
}
std::construct_at(slot_ptr(head), std::move(val));
head_.store(next, std::memory_order_release);
return true;
}
// Consumer side — pop returns nullopt when the buffer is empty.
[[nodiscard]] std::optional<T> pop() noexcept(
std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
{
const std::size_t tail = tail_.load(std::memory_order_relaxed);
if (tail == head_.load(std::memory_order_acquire)) return std::nullopt;
if (tail == head_.load(std::memory_order_acquire)) {
return std::nullopt;
}
T val{std::move(*slot_ptr(tail))};
std::destroy_at(slot_ptr(tail));
tail_.store((tail + 1) & mask_, std::memory_order_release);
@@ -92,88 +206,157 @@ private:
std::byte storage[sizeof(T)];
};
// Pad to separate cache lines to avoid false sharing.
alignas(64) std::atomic<std::size_t> head_{0};
alignas(64) std::atomic<std::size_t> tail_{0};
alignas(64) std::atomic<bool> closed_{false};
Slot storage_[N];
};
// ── MpscRing<T, N> ────────────────────────────────────────────────────────────
// Multi-producer / single-consumer ring buffer using a compare-exchange loop
// on the head pointer. Consumer is still single-threaded.
// Bounded multi-producer / single-consumer ring buffer with per-slot sequence
// publication and non-spinning try_pop() / pop() semantics.
// Consumer destruction requires producers to have quiesced.
template <typename T, std::size_t N>
requires(N >= 2 && (N & (N - 1)) == 0)
class MpscRing
{
private:
struct Slot
{
std::atomic<std::size_t> seq{0};
alignas(alignof(T)) std::byte storage[sizeof(T)];
};
public:
MpscRing() = default;
MpscRing() noexcept
{
for (std::size_t i = 0; i < N; ++i) {
slots_[i].seq.store(i, std::memory_order_relaxed);
}
}
MpscRing(const MpscRing&) = delete;
MpscRing& operator=(const MpscRing&) = delete;
[[nodiscard]] bool push(T val) noexcept(
std::is_nothrow_move_constructible_v<T>)
~MpscRing()
{
std::size_t head = head_.load(std::memory_order_relaxed);
std::size_t next;
do {
next = (head + 1) & mask_;
if (next == tail_.load(std::memory_order_acquire)) return false;
} while (!head_.compare_exchange_weak(head, next,
std::memory_order_acq_rel,
std::memory_order_relaxed));
std::construct_at(slot_ptr(head), std::move(val));
// Signal that this slot is ready.
ready_[head].store(true, std::memory_order_release);
return true;
std::size_t pos = dequeue_pos_.load(std::memory_order_acquire);
for (std::size_t count = 0; count < N; ++count) {
Slot& slot = slots_[pos & mask_];
if (slot.seq.load(std::memory_order_acquire) != pos + 1) {
break;
}
std::destroy_at(slot_ptr(slot));
++pos;
}
}
void close() noexcept { closed_.store(true, std::memory_order_release); }
[[nodiscard]] bool is_closed() const noexcept
{
return closed_.load(std::memory_order_acquire);
}
[[nodiscard]] PushStatus try_push(T val) noexcept(
std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
requires(std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
{
Slot* slot = nullptr;
std::size_t pos = enqueue_pos_.load(std::memory_order_relaxed);
for (;;) {
if (closed_.load(std::memory_order_acquire)) {
return PushStatus::closed;
}
slot = &slots_[pos & mask_];
const std::size_t seq = slot->seq.load(std::memory_order_acquire);
const std::ptrdiff_t diff =
static_cast<std::ptrdiff_t>(seq - pos);
if (diff == 0) {
if (enqueue_pos_.compare_exchange_weak(
pos, pos + 1,
std::memory_order_acq_rel,
std::memory_order_relaxed)) {
break;
}
} else if (diff < 0) {
return PushStatus::full;
} else {
pos = enqueue_pos_.load(std::memory_order_relaxed);
}
}
std::construct_at(slot_ptr(*slot), std::move(val));
slot->seq.store(pos + 1, std::memory_order_release);
return PushStatus::ok;
}
[[nodiscard]] PopResult<T> try_pop() noexcept(
std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
requires(std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
{
const std::size_t pos = dequeue_pos_.load(std::memory_order_relaxed);
Slot& slot = slots_[pos & mask_];
const std::size_t seq = slot.seq.load(std::memory_order_acquire);
const std::ptrdiff_t diff =
static_cast<std::ptrdiff_t>(seq - (pos + 1));
if (diff == 0) {
T val{std::move(*slot_ptr(slot))};
std::destroy_at(slot_ptr(slot));
dequeue_pos_.store(pos + 1, std::memory_order_release);
slot.seq.store(pos + N, std::memory_order_release);
return PopResult<T>{PopStatus::ok, std::move(val)};
}
const std::size_t enq = enqueue_pos_.load(std::memory_order_acquire);
if (static_cast<std::ptrdiff_t>(enq - pos) > 0) {
return PopResult<T>{PopStatus::pending, std::nullopt};
}
return PopResult<T>{
closed_.load(std::memory_order_acquire) ? PopStatus::closed : PopStatus::empty,
std::nullopt};
}
[[nodiscard]] bool push(T val) noexcept(
std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
{
return try_push(std::move(val)) == PushStatus::ok;
}
[[nodiscard]] std::optional<T> pop() noexcept(
std::is_nothrow_move_constructible_v<T>)
std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
{
const std::size_t tail = tail_.load(std::memory_order_relaxed);
if (tail == head_.load(std::memory_order_acquire)) return std::nullopt;
// Spin until the producing thread has written the value.
while (!ready_[tail].load(std::memory_order_acquire)) {
// wait — producer is still copying; this is still wait-free on the
// hot path (single iteration in practice).
}
T val{std::move(*slot_ptr(tail))};
std::destroy_at(slot_ptr(tail));
ready_[tail].store(false, std::memory_order_release);
tail_.store((tail + 1) & mask_, std::memory_order_release);
return val;
return try_pop().value;
}
[[nodiscard]] bool empty() const noexcept
{
return tail_.load(std::memory_order_acquire) ==
head_.load(std::memory_order_acquire);
return dequeue_pos_.load(std::memory_order_acquire) ==
enqueue_pos_.load(std::memory_order_acquire);
}
[[nodiscard]] static constexpr std::size_t capacity() noexcept
{
return N - 1;
return N;
}
private:
T* slot_ptr(std::size_t i) noexcept
static T* slot_ptr(Slot& slot) noexcept
{
return std::launder(reinterpret_cast<T*>(&storage_[i]));
return std::launder(reinterpret_cast<T*>(&slot.storage));
}
static constexpr std::size_t mask_ = N - 1;
struct alignas(alignof(T)) Slot
{
std::byte storage[sizeof(T)];
};
alignas(64) std::atomic<std::size_t> head_{0};
alignas(64) std::atomic<std::size_t> tail_{0};
Slot storage_[N];
std::atomic<bool> ready_[N]{};
alignas(64) std::atomic<std::size_t> enqueue_pos_{0};
alignas(64) std::atomic<std::size_t> dequeue_pos_{0};
alignas(64) std::atomic<bool> closed_{false};
Slot slots_[N];
};
} // namespace Void::Ring