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,203 +1,401 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Memory/Resource.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
#include <bit>
|
#include <bit>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <limits>
|
||||||
|
#include <memory>
|
||||||
|
#include <memory_resource>
|
||||||
|
#include <new>
|
||||||
#include <span>
|
#include <span>
|
||||||
#include <unordered_map>
|
|
||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Void::BufferPool
|
namespace Void::BufferPool
|
||||||
{
|
{
|
||||||
|
|
||||||
// ── BufferPool<T>
|
enum class BufferPoolError : std::uint8_t
|
||||||
// ───────────────────────────────────────────────────────────── A pool of
|
{
|
||||||
// reusable, variable-length buffers of T — e.g. audio sample blocks (int16
|
request_too_large,
|
||||||
// / float). Distinct from Containers/Pool.hpp's ObjectPool, which pools
|
budget_exceeded,
|
||||||
// fixed-size *objects*: this pools backing storage sized by request.
|
allocation_failed,
|
||||||
//
|
size_overflow
|
||||||
// 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.
|
|
||||||
|
|
||||||
template <typename T> class BufferPool
|
// ── BufferPool<T> ─────────────────────────────────────────────────────────────
|
||||||
{
|
// A pool of reusable, variable-length buffers of T with stationary shared state,
|
||||||
public:
|
// 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;
|
struct Stats
|
||||||
BufferPool& operator=(const BufferPool&) = delete;
|
{
|
||||||
BufferPool(BufferPool&&) = default;
|
std::uint64_t allocations = 0; // fresh storage allocated
|
||||||
BufferPool& operator=(BufferPool&&) = default;
|
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 {
|
private:
|
||||||
std::uint64_t allocations = 0; // fresh storage allocated
|
struct Node
|
||||||
std::uint64_t reuses = 0; // requests served from a bucket
|
{
|
||||||
std::size_t pooled = 0; // buffers currently idle in buckets
|
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
|
static constexpr std::size_t kBlockAlign =
|
||||||
// drop.
|
(alignof(Node) > alignof(T)) ? alignof(Node) : alignof(T);
|
||||||
class Buffer
|
static constexpr std::size_t kDataOffset =
|
||||||
{
|
((sizeof(Node) + alignof(T) - 1) / alignof(T)) * alignof(T);
|
||||||
public:
|
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;
|
struct State
|
||||||
Buffer& operator=(const Buffer&) = delete;
|
{
|
||||||
|
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
|
State(std::pmr::memory_resource* res, Limits lim) noexcept
|
||||||
: pool_{other.pool_},
|
: upstream{res ? res : std::pmr::get_default_resource()},
|
||||||
storage_{std::move(other.storage_)},
|
limits{lim}
|
||||||
size_{other.size_}
|
{
|
||||||
{
|
}
|
||||||
other.pool_ = nullptr;
|
|
||||||
other.size_ = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Buffer& operator=(Buffer&& other) noexcept
|
~State() { shrink(); }
|
||||||
{
|
|
||||||
if (this != &other) {
|
|
||||||
recycle();
|
|
||||||
pool_ = other.pool_;
|
|
||||||
storage_ = std::move(other.storage_);
|
|
||||||
size_ = other.size_;
|
|
||||||
other.pool_ = nullptr;
|
|
||||||
other.size_ = 0;
|
|
||||||
}
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
~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(); }
|
void shrink() noexcept
|
||||||
[[nodiscard]] const T* data() const noexcept
|
{
|
||||||
{
|
for (Node*& head : buckets) {
|
||||||
return storage_.data();
|
while (head) {
|
||||||
}
|
Node* node = head;
|
||||||
[[nodiscard]] std::size_t size() const noexcept
|
head = node->next;
|
||||||
{
|
idle_bytes -= node->payload_bytes;
|
||||||
return size_;
|
--pooled;
|
||||||
}
|
destroy_node(node);
|
||||||
[[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();
|
|
||||||
}
|
|
||||||
|
|
||||||
[[nodiscard]] T& operator[](std::size_t i) noexcept
|
void release(Node* node) noexcept
|
||||||
{
|
{
|
||||||
return storage_[i];
|
checked_out_bytes -= node->payload_bytes;
|
||||||
}
|
const std::size_t b = node->payload_bytes;
|
||||||
[[nodiscard]] const T&
|
const bool can_retain =
|
||||||
operator[](std::size_t i) const noexcept
|
owner_alive &&
|
||||||
{
|
b <= limits.max_idle_bytes &&
|
||||||
return storage_[i];
|
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(); }
|
public:
|
||||||
[[nodiscard]] T* end() noexcept { return data() + size_; }
|
BufferPool()
|
||||||
[[nodiscard]] const T* begin() const noexcept
|
: BufferPool(Limits{}, std::pmr::get_default_resource())
|
||||||
{
|
{
|
||||||
return data();
|
}
|
||||||
}
|
|
||||||
[[nodiscard]] const T* end() const noexcept
|
|
||||||
{
|
|
||||||
return data() + size_;
|
|
||||||
}
|
|
||||||
|
|
||||||
[[nodiscard]] std::span<T> span() noexcept
|
explicit BufferPool(
|
||||||
{
|
Limits limits,
|
||||||
return {data(), size_};
|
std::pmr::memory_resource* upstream = std::pmr::get_default_resource())
|
||||||
}
|
: state_{std::make_shared<State>(upstream, limits)}
|
||||||
[[nodiscard]] std::span<const T> span() const noexcept
|
{
|
||||||
{
|
}
|
||||||
return {data(), size_};
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
BufferPool(const BufferPool&) = delete;
|
||||||
std::size_t n) noexcept
|
BufferPool& operator=(const BufferPool&) = delete;
|
||||||
: pool_{pool}, storage_{std::move(storage)}, size_{n}
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
void recycle() noexcept
|
BufferPool(BufferPool&&) noexcept = default;
|
||||||
{
|
|
||||||
if (pool_) {
|
|
||||||
pool_->recycle(std::move(storage_));
|
|
||||||
pool_ = nullptr;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
BufferPool* pool_ = nullptr;
|
BufferPool& operator=(BufferPool&& other) noexcept
|
||||||
std::vector<T> storage_;
|
{
|
||||||
std::size_t size_ = 0;
|
if (this != &other) {
|
||||||
};
|
teardown();
|
||||||
|
state_ = std::move(other.state_);
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
// Hand out a buffer of logical length n (capacity rounded up to a
|
~BufferPool() { teardown(); }
|
||||||
// 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};
|
|
||||||
}
|
|
||||||
|
|
||||||
[[nodiscard]] Stats stats() const
|
// Owning view returned by acquire()/try_acquire(); recycles cleanly on drop.
|
||||||
{
|
class Buffer
|
||||||
std::size_t pooled = 0;
|
{
|
||||||
for (const auto& [cls, bucket] : free_) {
|
public:
|
||||||
pooled += bucket.size();
|
Buffer() = default;
|
||||||
}
|
Buffer(const Buffer&) = delete;
|
||||||
return Stats{allocations_, reuses_, pooled};
|
Buffer& operator=(const Buffer&) = delete;
|
||||||
}
|
|
||||||
|
|
||||||
// Drop all pooled (idle) storage. Outstanding Buffers are
|
Buffer(Buffer&& other) noexcept
|
||||||
// unaffected.
|
: state_{std::move(other.state_)},
|
||||||
void shrink() noexcept { free_.clear(); }
|
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
|
~Buffer() { recycle(); }
|
||||||
{
|
|
||||||
return n == 0 ? 0 : std::bit_ceil(n);
|
|
||||||
}
|
|
||||||
|
|
||||||
void recycle(std::vector<T> storage)
|
[[nodiscard]] T* data() noexcept
|
||||||
{
|
{
|
||||||
if (storage.empty()) {
|
return node_ ? data_ptr(node_) : nullptr;
|
||||||
return;
|
}
|
||||||
}
|
[[nodiscard]] const T* data() const noexcept
|
||||||
free_[storage.size()].push_back(std::move(storage));
|
{
|
||||||
}
|
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_;
|
[[nodiscard]] T& operator[](std::size_t i) noexcept { return data()[i]; }
|
||||||
std::uint64_t allocations_ = 0;
|
[[nodiscard]] const T& operator[](std::size_t i) const noexcept
|
||||||
std::uint64_t reuses_ = 0;
|
{
|
||||||
};
|
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
|
} // namespace Void::BufferPool
|
||||||
@@ -1,109 +1,272 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Memory/Resource.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <limits>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <memory_resource>
|
||||||
#include <new>
|
#include <new>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Void::Pool
|
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> ──────────────────────────────────────────────────
|
// ── ObjectPool<T, ChunkSize> ──────────────────────────────────────────────────
|
||||||
// A slab-based object pool. acquire() returns a unique_ptr<T> with a custom
|
// Slab-based object pool with stationary shared state so retained smart-pointer
|
||||||
// deleter that returns the object to the pool instead of freeing memory.
|
// leases remain safe if the pool is moved or destroyed before the leases drop.
|
||||||
// Objects are constructed in-place; the pool owns the backing storage.
|
// Recycling destroys T and relinks the slot with zero heap allocations.
|
||||||
//
|
|
||||||
// Thread-safety: NOT thread-safe. Add external synchronisation if needed.
|
|
||||||
|
|
||||||
template <typename T, std::size_t ChunkSize = 32>
|
template <typename T, std::size_t ChunkSize = 32>
|
||||||
|
requires (ChunkSize >= 1)
|
||||||
class ObjectPool
|
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:
|
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(const ObjectPool&) = delete;
|
||||||
ObjectPool& operator=(const ObjectPool&) = delete;
|
ObjectPool& operator=(const ObjectPool&) = delete;
|
||||||
ObjectPool(ObjectPool&&) = default;
|
ObjectPool(ObjectPool&&) noexcept = default;
|
||||||
ObjectPool& operator=(ObjectPool&&) = default;
|
ObjectPool& operator=(ObjectPool&&) noexcept = default;
|
||||||
|
|
||||||
~ObjectPool() = default;
|
~ObjectPool() = default;
|
||||||
|
|
||||||
struct Deleter
|
struct Deleter
|
||||||
{
|
{
|
||||||
ObjectPool* pool;
|
std::shared_ptr<State> state{};
|
||||||
void operator()(T* p) const noexcept { pool->release(p); }
|
void operator()(T* p) const noexcept
|
||||||
|
{
|
||||||
|
if (p && state) {
|
||||||
|
state->release(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
using Ptr = std::unique_ptr<T, Deleter>;
|
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>
|
template <typename... Args>
|
||||||
[[nodiscard]] Ptr acquire(Args&&... args)
|
[[nodiscard]] Ptr acquire(Args&&... args)
|
||||||
{
|
{
|
||||||
T* slot = pop_free();
|
auto r = try_acquire(std::forward<Args>(args)...);
|
||||||
if (!slot) {
|
if (!r) {
|
||||||
slot = allocate_slot();
|
throw std::bad_alloc{};
|
||||||
}
|
}
|
||||||
std::construct_at(slot, std::forward<Args>(args)...);
|
return std::move(*r);
|
||||||
return Ptr{slot, Deleter{this}};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] std::size_t capacity() const noexcept
|
[[nodiscard]] std::size_t capacity() const noexcept
|
||||||
{
|
{
|
||||||
return slabs_.size() * ChunkSize;
|
return state_ ? state_->total_slots : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] std::size_t available() const noexcept
|
[[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:
|
private:
|
||||||
void release(T* p) noexcept
|
std::shared_ptr<State> state_;
|
||||||
{
|
|
||||||
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_;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── FixedPool<T, N> ───────────────────────────────────────────────────────────
|
// ── FixedPool<T, N> ───────────────────────────────────────────────────────────
|
||||||
// A fixed-capacity pool allocated in-place (no heap after construction).
|
// Fixed-capacity pool allocated in-place (no heap after construction).
|
||||||
// Capacity is known at compile time; acquire() returns nullptr when full.
|
|
||||||
|
|
||||||
template <typename T, std::size_t N>
|
template <typename T, std::size_t N>
|
||||||
class FixedPool
|
class FixedPool
|
||||||
@@ -128,18 +291,41 @@ public:
|
|||||||
|
|
||||||
using Ptr = std::unique_ptr<T, Deleter>;
|
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>
|
template <typename... Args>
|
||||||
[[nodiscard]] Ptr acquire(Args&&... args) noexcept(
|
[[nodiscard]] Ptr acquire(Args&&... args) noexcept(
|
||||||
std::is_nothrow_constructible_v<T, Args...>)
|
std::is_nothrow_constructible_v<T, Args...>)
|
||||||
{
|
{
|
||||||
if (free_count_ == 0) return nullptr;
|
auto r = try_acquire(std::forward<Args>(args)...);
|
||||||
T* slot = free_[--free_count_];
|
if (!r) {
|
||||||
std::construct_at(slot, std::forward<Args>(args)...);
|
return nullptr;
|
||||||
return Ptr{slot, Deleter{this}};
|
}
|
||||||
|
return std::move(*r);
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; }
|
[[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; }
|
||||||
[[nodiscard]] std::size_t available() const noexcept { return free_count_; }
|
[[nodiscard]] std::size_t available() const noexcept { return free_count_; }
|
||||||
|
[[nodiscard]] std::size_t live() const noexcept { return N - free_count_; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void release(T* p) noexcept
|
void release(T* p) noexcept
|
||||||
@@ -158,8 +344,9 @@ private:
|
|||||||
std::byte storage[sizeof(T)];
|
std::byte storage[sizeof(T)];
|
||||||
};
|
};
|
||||||
|
|
||||||
Slot storage_[N];
|
static constexpr std::size_t kStorageCount = (N == 0) ? 1 : N;
|
||||||
T* free_[N];
|
std::array<Slot, kStorageCount> storage_{};
|
||||||
|
std::array<T*, kStorageCount> free_{};
|
||||||
std::size_t free_count_{0};
|
std::size_t free_count_{0};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -3,20 +3,52 @@
|
|||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
#include <new>
|
#include <new>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <type_traits>
|
#include <type_traits>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
namespace Void::Ring
|
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> ────────────────────────────────────────────────────────────
|
// ── SpscRing<T, N> ────────────────────────────────────────────────────────────
|
||||||
// Single-producer / single-consumer lock-free ring buffer.
|
// Single-producer / single-consumer wait-free bounded ring buffer.
|
||||||
// Capacity is N (must be a power of two). The buffer holds at most N-1 items.
|
// Capacity is N - 1 usable entries (N must be a power of two).
|
||||||
// All operations are wait-free.
|
|
||||||
|
|
||||||
template <typename T, std::size_t N>
|
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
|
class SpscRing
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
@@ -25,13 +57,89 @@ public:
|
|||||||
SpscRing(const SpscRing&) = delete;
|
SpscRing(const SpscRing&) = delete;
|
||||||
SpscRing& operator=(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)
|
[[nodiscard]] bool push(const T& val)
|
||||||
noexcept(std::is_nothrow_copy_constructible_v<T>)
|
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 head = head_.load(std::memory_order_relaxed);
|
||||||
const std::size_t next = (head + 1) & mask_;
|
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);
|
std::construct_at(slot_ptr(head), val);
|
||||||
head_.store(next, std::memory_order_release);
|
head_.store(next, std::memory_order_release);
|
||||||
return true;
|
return true;
|
||||||
@@ -40,21 +148,27 @@ public:
|
|||||||
[[nodiscard]] bool push(T&& val)
|
[[nodiscard]] bool push(T&& val)
|
||||||
noexcept(std::is_nothrow_move_constructible_v<T>)
|
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 head = head_.load(std::memory_order_relaxed);
|
||||||
const std::size_t next = (head + 1) & mask_;
|
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));
|
std::construct_at(slot_ptr(head), std::move(val));
|
||||||
head_.store(next, std::memory_order_release);
|
head_.store(next, std::memory_order_release);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Consumer side — pop returns nullopt when the buffer is empty.
|
|
||||||
[[nodiscard]] std::optional<T> pop() noexcept(
|
[[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>)
|
std::is_nothrow_destructible_v<T>)
|
||||||
{
|
{
|
||||||
const std::size_t tail = tail_.load(std::memory_order_relaxed);
|
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))};
|
T val{std::move(*slot_ptr(tail))};
|
||||||
std::destroy_at(slot_ptr(tail));
|
std::destroy_at(slot_ptr(tail));
|
||||||
tail_.store((tail + 1) & mask_, std::memory_order_release);
|
tail_.store((tail + 1) & mask_, std::memory_order_release);
|
||||||
@@ -92,88 +206,157 @@ private:
|
|||||||
std::byte storage[sizeof(T)];
|
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> head_{0};
|
||||||
alignas(64) std::atomic<std::size_t> tail_{0};
|
alignas(64) std::atomic<std::size_t> tail_{0};
|
||||||
|
alignas(64) std::atomic<bool> closed_{false};
|
||||||
Slot storage_[N];
|
Slot storage_[N];
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── MpscRing<T, N> ────────────────────────────────────────────────────────────
|
// ── MpscRing<T, N> ────────────────────────────────────────────────────────────
|
||||||
// Multi-producer / single-consumer ring buffer using a compare-exchange loop
|
// Bounded multi-producer / single-consumer ring buffer with per-slot sequence
|
||||||
// on the head pointer. Consumer is still single-threaded.
|
// publication and non-spinning try_pop() / pop() semantics.
|
||||||
|
// Consumer destruction requires producers to have quiesced.
|
||||||
|
|
||||||
template <typename T, std::size_t N>
|
template <typename T, std::size_t N>
|
||||||
requires(N >= 2 && (N & (N - 1)) == 0)
|
requires(N >= 2 && (N & (N - 1)) == 0)
|
||||||
class MpscRing
|
class MpscRing
|
||||||
{
|
{
|
||||||
|
private:
|
||||||
|
struct Slot
|
||||||
|
{
|
||||||
|
std::atomic<std::size_t> seq{0};
|
||||||
|
alignas(alignof(T)) std::byte storage[sizeof(T)];
|
||||||
|
};
|
||||||
|
|
||||||
public:
|
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(const MpscRing&) = delete;
|
||||||
MpscRing& operator=(const MpscRing&) = delete;
|
MpscRing& operator=(const MpscRing&) = delete;
|
||||||
|
|
||||||
[[nodiscard]] bool push(T val) noexcept(
|
~MpscRing()
|
||||||
std::is_nothrow_move_constructible_v<T>)
|
|
||||||
{
|
{
|
||||||
std::size_t head = head_.load(std::memory_order_relaxed);
|
std::size_t pos = dequeue_pos_.load(std::memory_order_acquire);
|
||||||
std::size_t next;
|
for (std::size_t count = 0; count < N; ++count) {
|
||||||
do {
|
Slot& slot = slots_[pos & mask_];
|
||||||
next = (head + 1) & mask_;
|
if (slot.seq.load(std::memory_order_acquire) != pos + 1) {
|
||||||
if (next == tail_.load(std::memory_order_acquire)) return false;
|
break;
|
||||||
} while (!head_.compare_exchange_weak(head, next,
|
}
|
||||||
std::memory_order_acq_rel,
|
std::destroy_at(slot_ptr(slot));
|
||||||
std::memory_order_relaxed));
|
++pos;
|
||||||
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;
|
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(
|
[[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);
|
return try_pop().value;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] bool empty() const noexcept
|
[[nodiscard]] bool empty() const noexcept
|
||||||
{
|
{
|
||||||
return tail_.load(std::memory_order_acquire) ==
|
return dequeue_pos_.load(std::memory_order_acquire) ==
|
||||||
head_.load(std::memory_order_acquire);
|
enqueue_pos_.load(std::memory_order_acquire);
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] static constexpr std::size_t capacity() noexcept
|
[[nodiscard]] static constexpr std::size_t capacity() noexcept
|
||||||
{
|
{
|
||||||
return N - 1;
|
return N;
|
||||||
}
|
}
|
||||||
|
|
||||||
private:
|
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;
|
static constexpr std::size_t mask_ = N - 1;
|
||||||
|
|
||||||
struct alignas(alignof(T)) Slot
|
alignas(64) std::atomic<std::size_t> enqueue_pos_{0};
|
||||||
{
|
alignas(64) std::atomic<std::size_t> dequeue_pos_{0};
|
||||||
std::byte storage[sizeof(T)];
|
alignas(64) std::atomic<bool> closed_{false};
|
||||||
};
|
Slot slots_[N];
|
||||||
|
|
||||||
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]{};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace Void::Ring
|
} // namespace Void::Ring
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
void_add_module(Containers
|
void_add_module(Containers
|
||||||
INTERNAL_DEPS Core
|
INTERNAL_DEPS Core Memory
|
||||||
)
|
)
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
#include <Void/Containers/BufferPool.hpp>
|
#include <Void/Containers/BufferPool.hpp>
|
||||||
|
#include <Void/Memory/BudgetResource.hpp>
|
||||||
#include <Void/Testing/Assert.hpp>
|
#include <Void/Testing/Assert.hpp>
|
||||||
#include <Void/Testing/Suite.hpp>
|
#include <Void/Testing/Suite.hpp>
|
||||||
|
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
#include <limits>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
namespace
|
namespace
|
||||||
{
|
{
|
||||||
@@ -82,5 +85,92 @@ namespace
|
|||||||
pool.shrink();
|
pool.shrink();
|
||||||
Void::Testing::expect_eq(pool.stats().pooled, std::size_t{0});
|
Void::Testing::expect_eq(pool.stats().pooled, std::size_t{0});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Test leases_survive_pool_move_and_destruction()
|
||||||
|
{
|
||||||
|
Void::Memory::BudgetResource budget{65536};
|
||||||
|
BufferPool<std::uint32_t>::Buffer retained;
|
||||||
|
{
|
||||||
|
BufferPool<std::uint32_t> p1{&budget};
|
||||||
|
auto b = p1.try_acquire(64);
|
||||||
|
Void::Testing::require(b.has_value());
|
||||||
|
(*b)[0] = 0xCAFEBABEu;
|
||||||
|
auto p2 = std::move(p1);
|
||||||
|
retained = std::move(*b);
|
||||||
|
Void::Testing::expect_eq(p2.stats().allocations,
|
||||||
|
std::uint64_t{1});
|
||||||
|
}
|
||||||
|
// Pool destroyed; retained buffer still intact and frees cleanly on drop.
|
||||||
|
Void::Testing::expect_eq(retained[0], 0xCAFEBABEu);
|
||||||
|
Void::Testing::expect(budget.stats().committed_live > 0);
|
||||||
|
retained = BufferPool<std::uint32_t>::Buffer{};
|
||||||
|
Void::Testing::expect_eq(budget.stats().committed_live,
|
||||||
|
std::size_t{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
Test enforces_request_idle_total_limits_and_overflow()
|
||||||
|
{
|
||||||
|
using Void::BufferPool::BufferPoolError;
|
||||||
|
|
||||||
|
BufferPool<std::uint64_t> small_pool{
|
||||||
|
BufferPool<std::uint64_t>::Limits{
|
||||||
|
.max_request_bytes = 256,
|
||||||
|
.max_idle_bytes = 256,
|
||||||
|
.max_total_bytes = 512}};
|
||||||
|
|
||||||
|
const auto ovf = small_pool.try_acquire(
|
||||||
|
std::numeric_limits<std::size_t>::max());
|
||||||
|
Void::Testing::expect(
|
||||||
|
!ovf.has_value() &&
|
||||||
|
ovf.error() == BufferPoolError::size_overflow);
|
||||||
|
|
||||||
|
const auto too_big = small_pool.try_acquire(64); // 512B > 256B
|
||||||
|
Void::Testing::expect(
|
||||||
|
!too_big.has_value() &&
|
||||||
|
too_big.error() == BufferPoolError::request_too_large);
|
||||||
|
|
||||||
|
auto a = small_pool.try_acquire(32); // 256B
|
||||||
|
auto b = small_pool.try_acquire(32); // 256B (total 512B)
|
||||||
|
auto c = small_pool.try_acquire(32); // exceeds 512B
|
||||||
|
Void::Testing::require(a.has_value() && b.has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
!c.has_value() &&
|
||||||
|
c.error() == BufferPoolError::budget_exceeded);
|
||||||
|
|
||||||
|
a = {}; // fits in max_idle_bytes=256B
|
||||||
|
b = {}; // exceeds max_idle_bytes=256B -> dropped_on_return
|
||||||
|
Void::Testing::expect_eq(small_pool.stats().pooled,
|
||||||
|
std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(small_pool.stats().idle_bytes,
|
||||||
|
std::size_t{256});
|
||||||
|
Void::Testing::expect_eq(small_pool.stats().dropped_on_return,
|
||||||
|
std::uint64_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
Test budget_resource_zero_allocs_on_reuse_and_handles_oom()
|
||||||
|
{
|
||||||
|
using Void::BufferPool::BufferPoolError;
|
||||||
|
|
||||||
|
Void::Memory::BudgetResource budget{1024};
|
||||||
|
BufferPool<std::uint8_t> pool{&budget};
|
||||||
|
{
|
||||||
|
auto b = pool.try_acquire(256);
|
||||||
|
Void::Testing::require(b.has_value());
|
||||||
|
}
|
||||||
|
const auto allocs = budget.stats().allocations;
|
||||||
|
Void::Testing::expect_eq(allocs, std::uint64_t{1});
|
||||||
|
|
||||||
|
{
|
||||||
|
auto b2 = pool.try_acquire(200); // same class 256
|
||||||
|
Void::Testing::require(b2.has_value());
|
||||||
|
Void::Testing::expect_eq(budget.stats().allocations, allocs);
|
||||||
|
Void::Testing::expect_eq(pool.stats().reuses, std::uint64_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto fail_alloc = pool.try_acquire(2048);
|
||||||
|
Void::Testing::expect(
|
||||||
|
!fail_alloc.has_value() &&
|
||||||
|
fail_alloc.error() == BufferPoolError::allocation_failed);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
} // namespace
|
} // namespace
|
||||||
@@ -1,8 +1,13 @@
|
|||||||
#include <Void/Containers/Pool.hpp>
|
#include <Void/Containers/Pool.hpp>
|
||||||
|
#include <Void/Memory/BudgetResource.hpp>
|
||||||
#include <Void/Testing/Assert.hpp>
|
#include <Void/Testing/Assert.hpp>
|
||||||
#include <Void/Testing/Test.hpp>
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <stdexcept>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
// ── ObjectPool ────────────────────────────────────────────────────────────────
|
// ── ObjectPool ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -101,3 +106,134 @@ Void::Testing::Test fixed_pool_reuse_after_release()
|
|||||||
Void::Testing::expect(p3 != nullptr);
|
Void::Testing::expect(p3 != nullptr);
|
||||||
Void::Testing::expect_eq(*p3, 3);
|
Void::Testing::expect_eq(*p3, 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
struct TrackedObject
|
||||||
|
{
|
||||||
|
int value{0};
|
||||||
|
std::atomic<int>* dtor_count{nullptr};
|
||||||
|
bool should_throw{false};
|
||||||
|
|
||||||
|
TrackedObject(int v, std::atomic<int>* dc, bool fail = false)
|
||||||
|
: value{v}, dtor_count{dc}, should_throw{fail}
|
||||||
|
{
|
||||||
|
if (should_throw) {
|
||||||
|
throw std::runtime_error{"ctor failure"};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
~TrackedObject()
|
||||||
|
{
|
||||||
|
if (dtor_count) {
|
||||||
|
dtor_count->fetch_add(1, std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test object_pool_leases_survive_move_and_owner_destruction()
|
||||||
|
{
|
||||||
|
std::atomic<int> dtors{0};
|
||||||
|
Void::Pool::ObjectPool<TrackedObject, 4>::Ptr retained_a;
|
||||||
|
Void::Pool::ObjectPool<TrackedObject, 4>::Ptr retained_b;
|
||||||
|
|
||||||
|
{
|
||||||
|
Void::Pool::ObjectPool<TrackedObject, 4> p1;
|
||||||
|
auto a = p1.try_acquire(11, &dtors);
|
||||||
|
Void::Testing::require(a.has_value());
|
||||||
|
retained_a = std::move(*a);
|
||||||
|
|
||||||
|
auto p2 = std::move(p1);
|
||||||
|
Void::Testing::expect_eq(p2.live(), std::size_t{1});
|
||||||
|
auto b = p2.try_acquire(22, &dtors);
|
||||||
|
Void::Testing::require(b.has_value());
|
||||||
|
retained_b = std::move(*b);
|
||||||
|
Void::Testing::expect_eq(p2.live(), std::size_t{2});
|
||||||
|
} // p2 destroyed while retained_a and retained_b remain live
|
||||||
|
|
||||||
|
Void::Testing::expect_eq(dtors.load(), 0);
|
||||||
|
Void::Testing::expect_eq(retained_a->value, 11);
|
||||||
|
Void::Testing::expect_eq(retained_b->value, 22);
|
||||||
|
retained_a.reset();
|
||||||
|
Void::Testing::expect_eq(dtors.load(), 1);
|
||||||
|
retained_b.reset();
|
||||||
|
Void::Testing::expect_eq(dtors.load(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test object_pool_enforces_limits_budget_zero_alloc_recycle_and_ctor_throw()
|
||||||
|
{
|
||||||
|
using Void::Pool::PoolError;
|
||||||
|
|
||||||
|
// Constructor exception rolls back slot cleanly without leaking live count.
|
||||||
|
std::atomic<int> dtors{0};
|
||||||
|
Void::Pool::ObjectPool<TrackedObject, 4> exc_pool{
|
||||||
|
Void::Pool::ObjectPoolLimits{.max_live = 2, .max_total_slots = 4}};
|
||||||
|
bool caught = false;
|
||||||
|
try {
|
||||||
|
(void)exc_pool.try_acquire(1, &dtors, true);
|
||||||
|
} catch (const std::runtime_error&) {
|
||||||
|
caught = true;
|
||||||
|
}
|
||||||
|
Void::Testing::expect(caught);
|
||||||
|
Void::Testing::expect_eq(exc_pool.live(), std::size_t{0});
|
||||||
|
Void::Testing::expect_eq(exc_pool.available(), std::size_t{4});
|
||||||
|
Void::Testing::expect_eq(dtors.load(), 0);
|
||||||
|
|
||||||
|
// BudgetResource tracks allocations: zero upstream allocs on recycle & reuse.
|
||||||
|
Void::Memory::BudgetResource budget{1024};
|
||||||
|
Void::Pool::ObjectPool<int, 2> budgeted{
|
||||||
|
&budget,
|
||||||
|
Void::Pool::ObjectPoolLimits{.max_live = 4, .max_total_slots = 16}};
|
||||||
|
{
|
||||||
|
auto p1 = budgeted.try_acquire(10);
|
||||||
|
auto p2 = budgeted.try_acquire(20);
|
||||||
|
Void::Testing::require(p1.has_value() && p2.has_value());
|
||||||
|
Void::Testing::expect_eq(budgeted.live(), std::size_t{2});
|
||||||
|
}
|
||||||
|
const auto allocs_after_first_slab = budget.stats().allocations;
|
||||||
|
Void::Testing::expect_eq(allocs_after_first_slab, std::uint64_t{1});
|
||||||
|
{
|
||||||
|
auto r1 = budgeted.try_acquire(30);
|
||||||
|
auto r2 = budgeted.try_acquire(40);
|
||||||
|
Void::Testing::require(r1.has_value() && r2.has_value());
|
||||||
|
Void::Testing::expect_eq(budget.stats().allocations, allocs_after_first_slab);
|
||||||
|
}
|
||||||
|
|
||||||
|
// max_live limit triggers exhausted.
|
||||||
|
Void::Pool::ObjectPool<int, 4> capped{
|
||||||
|
Void::Pool::ObjectPoolLimits{.max_live = 2, .max_total_slots = 4}};
|
||||||
|
auto c1 = capped.try_acquire(1);
|
||||||
|
auto c2 = capped.try_acquire(2);
|
||||||
|
auto c3 = capped.try_acquire(3);
|
||||||
|
Void::Testing::require(c1.has_value() && c2.has_value());
|
||||||
|
Void::Testing::expect(!c3.has_value() && c3.error() == PoolError::exhausted);
|
||||||
|
|
||||||
|
// Exhausted BudgetResource triggers allocation_failed.
|
||||||
|
Void::Memory::BudgetResource tiny_budget{0};
|
||||||
|
Void::Pool::ObjectPool<int, 4> oom_pool{&tiny_budget};
|
||||||
|
const auto oom = oom_pool.try_acquire(5);
|
||||||
|
Void::Testing::expect(!oom.has_value() && oom.error() == PoolError::allocation_failed);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test fixed_pool_try_acquire_and_throwing_ctor()
|
||||||
|
{
|
||||||
|
std::atomic<int> dtors{0};
|
||||||
|
Void::Pool::FixedPool<TrackedObject, 2> pool;
|
||||||
|
bool caught = false;
|
||||||
|
try {
|
||||||
|
(void)pool.try_acquire(7, &dtors, true);
|
||||||
|
} catch (const std::runtime_error&) {
|
||||||
|
caught = true;
|
||||||
|
}
|
||||||
|
Void::Testing::expect(caught);
|
||||||
|
Void::Testing::expect_eq(pool.available(), std::size_t{2});
|
||||||
|
Void::Testing::expect_eq(pool.live(), std::size_t{0});
|
||||||
|
|
||||||
|
auto a = pool.try_acquire(1, &dtors);
|
||||||
|
auto b = pool.try_acquire(2, &dtors);
|
||||||
|
auto c = pool.try_acquire(3, &dtors);
|
||||||
|
Void::Testing::require(a.has_value() && b.has_value());
|
||||||
|
Void::Testing::expect(!c.has_value() && c.error() == Void::Pool::PoolError::exhausted);
|
||||||
|
Void::Testing::expect_eq(pool.live(), std::size_t{2});
|
||||||
|
}
|
||||||
@@ -2,8 +2,11 @@
|
|||||||
#include <Void/Testing/Assert.hpp>
|
#include <Void/Testing/Assert.hpp>
|
||||||
#include <Void/Testing/Test.hpp>
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstdint>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
#include <utility>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
// ── SpscRing ──────────────────────────────────────────────────────────────────
|
// ── SpscRing ──────────────────────────────────────────────────────────────────
|
||||||
@@ -144,3 +147,173 @@ Void::Testing::Test mpsc_two_producers_one_consumer()
|
|||||||
p1.join(); p2.join(); consumer.join();
|
p1.join(); p2.join(); consumer.join();
|
||||||
Void::Testing::expect_eq(total.load(), N * 3); // N×1 + N×2 = 3N
|
Void::Testing::expect_eq(total.load(), N * 3); // N×1 + N×2 = 3N
|
||||||
}
|
}
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
struct CountedItem
|
||||||
|
{
|
||||||
|
int value{0};
|
||||||
|
std::atomic<int>* dtors{nullptr};
|
||||||
|
|
||||||
|
CountedItem(int v, std::atomic<int>* d) noexcept : value{v}, dtors{d} {}
|
||||||
|
CountedItem(CountedItem&& o) noexcept
|
||||||
|
: value{o.value}, dtors{std::exchange(o.dtors, nullptr)}
|
||||||
|
{
|
||||||
|
}
|
||||||
|
CountedItem& operator=(CountedItem&& o) noexcept
|
||||||
|
{
|
||||||
|
if (this != &o) {
|
||||||
|
if (dtors) dtors->fetch_add(1, std::memory_order_relaxed);
|
||||||
|
value = o.value;
|
||||||
|
dtors = std::exchange(o.dtors, nullptr);
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
~CountedItem()
|
||||||
|
{
|
||||||
|
if (dtors) {
|
||||||
|
dtors->fetch_add(1, std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct DelayedMoveItem
|
||||||
|
{
|
||||||
|
int id{0};
|
||||||
|
std::atomic<bool>* entered_move{nullptr};
|
||||||
|
std::atomic<bool>* release_move{nullptr};
|
||||||
|
|
||||||
|
DelayedMoveItem() noexcept = default;
|
||||||
|
DelayedMoveItem(int v, std::atomic<bool>* entered, std::atomic<bool>* release) noexcept
|
||||||
|
: id{v}, entered_move{entered}, release_move{release}
|
||||||
|
{
|
||||||
|
}
|
||||||
|
DelayedMoveItem(DelayedMoveItem&& other) noexcept
|
||||||
|
: id{other.id},
|
||||||
|
entered_move{nullptr},
|
||||||
|
release_move{nullptr}
|
||||||
|
{
|
||||||
|
if (other.entered_move && other.release_move) {
|
||||||
|
other.entered_move->store(true, std::memory_order_release);
|
||||||
|
while (!other.release_move->load(std::memory_order_acquire)) {
|
||||||
|
std::this_thread::yield();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DelayedMoveItem& operator=(DelayedMoveItem&&) noexcept = default;
|
||||||
|
~DelayedMoveItem() noexcept = default;
|
||||||
|
};
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test spsc_and_mpsc_close_wraparound_and_destructor_cleanup()
|
||||||
|
{
|
||||||
|
using Void::Ring::PopStatus;
|
||||||
|
using Void::Ring::PushStatus;
|
||||||
|
|
||||||
|
std::atomic<int> spsc_dtors{0};
|
||||||
|
{
|
||||||
|
Void::Ring::SpscRing<CountedItem, 4> spsc;
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
Void::Testing::expect(spsc.try_push(CountedItem{i, &spsc_dtors}) == PushStatus::ok);
|
||||||
|
auto popped = spsc.try_pop();
|
||||||
|
Void::Testing::expect(popped.status == PopStatus::ok && popped.value->value == i);
|
||||||
|
}
|
||||||
|
Void::Testing::expect(spsc.try_push(CountedItem{100, &spsc_dtors}) == PushStatus::ok);
|
||||||
|
Void::Testing::expect(spsc.try_push(CountedItem{101, &spsc_dtors}) == PushStatus::ok);
|
||||||
|
spsc.close();
|
||||||
|
Void::Testing::expect(spsc.try_push(CountedItem{102, &spsc_dtors}) == PushStatus::closed);
|
||||||
|
}
|
||||||
|
Void::Testing::expect_eq(spsc_dtors.load(), 19);
|
||||||
|
|
||||||
|
std::atomic<int> mpsc_dtors{0};
|
||||||
|
{
|
||||||
|
Void::Ring::MpscRing<CountedItem, 4> mpsc;
|
||||||
|
for (int i = 0; i < 20; ++i) {
|
||||||
|
Void::Testing::expect(mpsc.try_push(CountedItem{i, &mpsc_dtors}) == PushStatus::ok);
|
||||||
|
auto popped = mpsc.try_pop();
|
||||||
|
Void::Testing::expect(popped.status == PopStatus::ok && popped.value->value == i);
|
||||||
|
}
|
||||||
|
Void::Testing::expect(mpsc.try_push(CountedItem{200, &mpsc_dtors}) == PushStatus::ok);
|
||||||
|
Void::Testing::expect(mpsc.try_push(CountedItem{201, &mpsc_dtors}) == PushStatus::ok);
|
||||||
|
mpsc.close();
|
||||||
|
Void::Testing::expect(mpsc.try_push(CountedItem{202, &mpsc_dtors}) == PushStatus::closed);
|
||||||
|
}
|
||||||
|
Void::Testing::expect_eq(mpsc_dtors.load(), 23);
|
||||||
|
}
|
||||||
|
|
||||||
|
// @tag threading
|
||||||
|
Void::Testing::Test mpsc_delayed_producer_returns_pending_without_spinning()
|
||||||
|
{
|
||||||
|
using Void::Ring::PopStatus;
|
||||||
|
using Void::Ring::PushStatus;
|
||||||
|
|
||||||
|
Void::Ring::MpscRing<DelayedMoveItem, 8> ring;
|
||||||
|
std::atomic<bool> entered{false};
|
||||||
|
std::atomic<bool> release{false};
|
||||||
|
|
||||||
|
std::thread producer([&] {
|
||||||
|
Void::Testing::expect(ring.try_push(DelayedMoveItem{77, &entered, &release}) == PushStatus::ok);
|
||||||
|
});
|
||||||
|
|
||||||
|
while (!entered.load(std::memory_order_acquire)) {
|
||||||
|
std::this_thread::yield();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Slot 0 is reserved (enqueue_pos_ == 1) but not yet published: must return pending immediately.
|
||||||
|
const auto pending = ring.try_pop();
|
||||||
|
Void::Testing::expect(pending.status == PopStatus::pending);
|
||||||
|
Void::Testing::expect(!pending.has_value());
|
||||||
|
|
||||||
|
release.store(true, std::memory_order_release);
|
||||||
|
producer.join();
|
||||||
|
|
||||||
|
const auto ready = ring.try_pop();
|
||||||
|
Void::Testing::expect(ready.status == PopStatus::ok);
|
||||||
|
Void::Testing::require(ready.has_value());
|
||||||
|
Void::Testing::expect_eq(ready.value->id, 77);
|
||||||
|
|
||||||
|
ring.close();
|
||||||
|
const auto closed = ring.try_pop();
|
||||||
|
Void::Testing::expect(closed.status == PopStatus::closed);
|
||||||
|
}
|
||||||
|
|
||||||
|
// @tag threading
|
||||||
|
Void::Testing::Test mpsc_high_contention_wraparound_stress()
|
||||||
|
{
|
||||||
|
Void::Ring::MpscRing<std::uint64_t, 16> ring;
|
||||||
|
constexpr int kProducers = 4;
|
||||||
|
constexpr std::uint64_t kPerProducer = 200;
|
||||||
|
std::vector<std::thread> producers;
|
||||||
|
for (int p = 0; p < kProducers; ++p) {
|
||||||
|
producers.emplace_back([&, p] {
|
||||||
|
for (std::uint64_t i = 0; i < kPerProducer; ++i) {
|
||||||
|
const std::uint64_t val =
|
||||||
|
(static_cast<std::uint64_t>(p) << 32) | i;
|
||||||
|
while (ring.try_push(val) != Void::Ring::PushStatus::ok) {
|
||||||
|
std::this_thread::yield();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint64_t consumed = 0;
|
||||||
|
std::uint64_t xor_sum = 0;
|
||||||
|
while (consumed < kProducers * kPerProducer) {
|
||||||
|
auto r = ring.try_pop();
|
||||||
|
if (r.status == Void::Ring::PopStatus::ok) {
|
||||||
|
xor_sum ^= *r.value;
|
||||||
|
++consumed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (auto& t : producers) {
|
||||||
|
t.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint64_t expected_xor = 0;
|
||||||
|
for (int p = 0; p < kProducers; ++p) {
|
||||||
|
for (std::uint64_t i = 0; i < kPerProducer; ++i) {
|
||||||
|
expected_xor ^= (static_cast<std::uint64_t>(p) << 32) | i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Void::Testing::expect_eq(xor_sum, expected_xor);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user