From 9ac76bbcf9f7367e3b0f1af346d62fba40c2a897 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 03:20:04 +0300 Subject: [PATCH] feat(Containers): fix pool lease lifetimes/budgets and non-spinning MPSC ring (M-CONTAINERS-02, M-CONTAINERS-03) --- include/Void/Containers/BufferPool.hpp | 526 ++++++++++++++------- include/Void/Containers/Pool.hpp | 319 ++++++++++--- include/Void/Containers/Ring.hpp | 291 +++++++++--- src/Containers/module.cmake | 2 +- tests/standalone/Containers/BufferPool.cpp | 90 ++++ tests/standalone/Containers/Pool.cpp | 136 ++++++ tests/standalone/Containers/Ring.cpp | 173 +++++++ 7 files changed, 1252 insertions(+), 285 deletions(-) diff --git a/include/Void/Containers/BufferPool.hpp b/include/Void/Containers/BufferPool.hpp index b4e1c83..17b72c0 100644 --- a/include/Void/Containers/BufferPool.hpp +++ b/include/Void/Containers/BufferPool.hpp @@ -1,203 +1,401 @@ #pragma once +#include + +#include +#include #include #include #include +#include +#include +#include +#include +#include #include -#include #include -#include namespace Void::BufferPool { - // ── BufferPool - // ───────────────────────────────────────────────────────────── 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 class BufferPool - { - public: +// ── BufferPool ───────────────────────────────────────────────────────────── +// 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 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( + reinterpret_cast(node) + kDataOffset); + } - Buffer(const Buffer&) = delete; - Buffer& operator=(const Buffer&) = delete; + struct State + { + std::pmr::memory_resource* upstream; + Limits limits; + std::array 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 span() noexcept - { - return {data(), size_}; - } - [[nodiscard]] std::span span() const noexcept - { - return {data(), size_}; - } + explicit BufferPool( + Limits limits, + std::pmr::memory_resource* upstream = std::pmr::get_default_resource()) + : state_{std::make_shared(upstream, limits)} + { + } - private: + explicit BufferPool( + Void::Memory::UnlimitedTag, + std::pmr::memory_resource* upstream = std::pmr::get_default_resource()) + : state_{std::make_shared( + upstream, + Limits{ + .max_request_bytes = std::numeric_limits::max(), + .max_idle_bytes = std::numeric_limits::max(), + .max_total_bytes = std::numeric_limits::max()})} + { + } - friend class BufferPool; + explicit BufferPool( + std::pmr::memory_resource* upstream, + Limits limits = {}) + : state_{std::make_shared(upstream, limits)} + { + } - Buffer(BufferPool* pool, std::vector 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 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 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 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>> 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 span() noexcept { return {data(), size_}; } + [[nodiscard]] std::span span() const noexcept + { + return {data(), size_}; + } + + private: + friend class BufferPool; + + Buffer(std::shared_ptr 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_{}; + Node* node_{nullptr}; + std::size_t size_{0}; + }; + + [[nodiscard]] std::expected + 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::max(); + constexpr std::size_t kMaxPow2 = + std::size_t{1} << (std::numeric_limits::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::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(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_; +}; } // namespace Void::BufferPool diff --git a/include/Void/Containers/Pool.hpp b/include/Void/Containers/Pool.hpp index a910664..b08a9d5 100644 --- a/include/Void/Containers/Pool.hpp +++ b/include/Void/Containers/Pool.hpp @@ -1,109 +1,272 @@ #pragma once +#include + +#include +#include #include #include +#include +#include +#include #include +#include #include #include -#include 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 ────────────────────────────────────────────────── -// A slab-based object pool. acquire() returns a unique_ptr 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 + 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(p); + push_free(s); + --live; + } + + Slot* allocate_slab(std::size_t count) noexcept + { + constexpr std::size_t kMaxSize = std::numeric_limits::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(raw)); + header->next = slabs; + header->slot_count = count; + header->alloc_bytes = bytes; + slabs = header; + total_slots += count; + allocated_bytes += bytes; + + auto* slots = reinterpret_cast( + static_cast(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(upstream, limits)} + { + } + + explicit ObjectPool( + Void::Memory::UnlimitedTag, + std::pmr::memory_resource* upstream = std::pmr::get_default_resource()) + : state_{std::make_shared( + upstream, + ObjectPoolLimits{ + .max_live = std::numeric_limits::max(), + .max_total_slots = std::numeric_limits::max()})} + { + } + + explicit ObjectPool( + std::pmr::memory_resource* upstream, + ObjectPoolLimits limits = {}) + : state_{std::make_shared(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{}; + void operator()(T* p) const noexcept + { + if (p && state) { + state->release(p); + } + } }; using Ptr = std::unique_ptr; + template + [[nodiscard]] std::expected 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(slot); + try { + std::construct_at(obj, std::forward(args)...); + } catch (...) { + state_->push_free(slot); + throw; + } + ++state_->live; + return Ptr{obj, Deleter{state_}}; + } + template [[nodiscard]] Ptr acquire(Args&&... args) { - T* slot = pop_free(); - if (!slot) { - slot = allocate_slot(); + auto r = try_acquire(std::forward(args)...); + if (!r) { + throw std::bad_alloc{}; } - std::construct_at(slot, std::forward(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(); - // Push all but the first slot into free_. - for (std::size_t i = 1; i < ChunkSize; ++i) { - free_.push_back(reinterpret_cast(&slab->storage[i])); - } - return reinterpret_cast(&slab->storage[0]); - } - - struct alignas(alignof(T)) Slot - { - std::byte storage[sizeof(T)]; - }; - - struct Slab - { - Slot storage[ChunkSize]; - }; - - std::vector> slabs_; - std::vector free_; + std::shared_ptr state_; }; // ── FixedPool ─────────────────────────────────────────────────────────── -// 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 class FixedPool @@ -128,18 +291,41 @@ public: using Ptr = std::unique_ptr; + template + [[nodiscard]] std::expected + try_acquire(Args&&... args) noexcept(std::is_nothrow_constructible_v) + { + if (free_count_ == 0) { + return std::unexpected{PoolError::exhausted}; + } + T* slot = free_[--free_count_]; + if constexpr (std::is_nothrow_constructible_v) { + std::construct_at(slot, std::forward(args)...); + } else { + try { + std::construct_at(slot, std::forward(args)...); + } catch (...) { + free_[free_count_++] = slot; + throw; + } + } + return Ptr{slot, Deleter{this}}; + } + template [[nodiscard]] Ptr acquire(Args&&... args) noexcept( std::is_nothrow_constructible_v) { - if (free_count_ == 0) return nullptr; - T* slot = free_[--free_count_]; - std::construct_at(slot, std::forward(args)...); - return Ptr{slot, Deleter{this}}; + auto r = try_acquire(std::forward(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 storage_{}; + std::array free_{}; std::size_t free_count_{0}; }; diff --git a/include/Void/Containers/Ring.hpp b/include/Void/Containers/Ring.hpp index a0f6b4e..e563e42 100644 --- a/include/Void/Containers/Ring.hpp +++ b/include/Void/Containers/Ring.hpp @@ -3,20 +3,52 @@ #include #include #include +#include +#include #include #include #include +#include namespace Void::Ring { +enum class PushStatus : std::uint8_t +{ + ok, + full, + closed +}; + +enum class PopStatus : std::uint8_t +{ + ok, + empty, + pending, + closed +}; + +template struct PopResult +{ + PopStatus status{PopStatus::empty}; + std::optional value{}; + + [[nodiscard]] constexpr bool has_value() const noexcept + { + return value.has_value(); + } + [[nodiscard]] constexpr explicit operator bool() const noexcept + { + return value.has_value(); + } +}; + // ── SpscRing ──────────────────────────────────────────────────────────── -// 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 - 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) + requires(std::is_nothrow_copy_constructible_v && + std::is_nothrow_destructible_v) + { + 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) + requires(std::is_nothrow_move_constructible_v && + std::is_nothrow_destructible_v) + { + 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 try_pop() noexcept( + std::is_nothrow_move_constructible_v && + std::is_nothrow_destructible_v) + requires(std::is_nothrow_move_constructible_v && + std::is_nothrow_destructible_v) + { + const std::size_t tail = tail_.load(std::memory_order_relaxed); + if (tail == head_.load(std::memory_order_acquire)) { + return PopResult{ + 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{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) { + 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) { + 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 pop() noexcept( std::is_nothrow_move_constructible_v && std::is_nothrow_destructible_v) { 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 head_{0}; alignas(64) std::atomic tail_{0}; + alignas(64) std::atomic closed_{false}; Slot storage_[N]; }; // ── MpscRing ──────────────────────────────────────────────────────────── -// 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 requires(N >= 2 && (N & (N - 1)) == 0) class MpscRing { +private: + struct Slot + { + std::atomic 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) + ~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 && + std::is_nothrow_destructible_v) + requires(std::is_nothrow_move_constructible_v && + std::is_nothrow_destructible_v) + { + 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(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 try_pop() noexcept( + std::is_nothrow_move_constructible_v && + std::is_nothrow_destructible_v) + requires(std::is_nothrow_move_constructible_v && + std::is_nothrow_destructible_v) + { + 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(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{PopStatus::ok, std::move(val)}; + } + const std::size_t enq = enqueue_pos_.load(std::memory_order_acquire); + if (static_cast(enq - pos) > 0) { + return PopResult{PopStatus::pending, std::nullopt}; + } + return PopResult{ + closed_.load(std::memory_order_acquire) ? PopStatus::closed : PopStatus::empty, + std::nullopt}; + } + + [[nodiscard]] bool push(T val) noexcept( + std::is_nothrow_move_constructible_v && + std::is_nothrow_destructible_v) + { + return try_push(std::move(val)) == PushStatus::ok; } [[nodiscard]] std::optional pop() noexcept( - std::is_nothrow_move_constructible_v) + std::is_nothrow_move_constructible_v && + std::is_nothrow_destructible_v) { - 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(&storage_[i])); + return std::launder(reinterpret_cast(&slot.storage)); } static constexpr std::size_t mask_ = N - 1; - struct alignas(alignof(T)) Slot - { - std::byte storage[sizeof(T)]; - }; - - alignas(64) std::atomic head_{0}; - alignas(64) std::atomic tail_{0}; - Slot storage_[N]; - std::atomic ready_[N]{}; + alignas(64) std::atomic enqueue_pos_{0}; + alignas(64) std::atomic dequeue_pos_{0}; + alignas(64) std::atomic closed_{false}; + Slot slots_[N]; }; } // namespace Void::Ring diff --git a/src/Containers/module.cmake b/src/Containers/module.cmake index f988cea..15d4f5c 100644 --- a/src/Containers/module.cmake +++ b/src/Containers/module.cmake @@ -1,3 +1,3 @@ void_add_module(Containers - INTERNAL_DEPS Core + INTERNAL_DEPS Core Memory ) diff --git a/tests/standalone/Containers/BufferPool.cpp b/tests/standalone/Containers/BufferPool.cpp index d3a86e1..ac5d1d6 100644 --- a/tests/standalone/Containers/BufferPool.cpp +++ b/tests/standalone/Containers/BufferPool.cpp @@ -1,8 +1,11 @@ #include +#include #include #include #include +#include +#include namespace { @@ -82,5 +85,92 @@ namespace pool.shrink(); Void::Testing::expect_eq(pool.stats().pooled, std::size_t{0}); } + + Test leases_survive_pool_move_and_destruction() + { + Void::Memory::BudgetResource budget{65536}; + BufferPool::Buffer retained; + { + BufferPool 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::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 small_pool{ + BufferPool::Limits{ + .max_request_bytes = 256, + .max_idle_bytes = 256, + .max_total_bytes = 512}}; + + const auto ovf = small_pool.try_acquire( + std::numeric_limits::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 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 diff --git a/tests/standalone/Containers/Pool.cpp b/tests/standalone/Containers/Pool.cpp index 8b6e858..7d23122 100644 --- a/tests/standalone/Containers/Pool.cpp +++ b/tests/standalone/Containers/Pool.cpp @@ -1,8 +1,13 @@ #include +#include #include #include +#include +#include +#include #include +#include // ── ObjectPool ──────────────────────────────────────────────────────────────── @@ -101,3 +106,134 @@ Void::Testing::Test fixed_pool_reuse_after_release() Void::Testing::expect(p3 != nullptr); Void::Testing::expect_eq(*p3, 3); } + +namespace +{ + struct TrackedObject + { + int value{0}; + std::atomic* dtor_count{nullptr}; + bool should_throw{false}; + + TrackedObject(int v, std::atomic* 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 dtors{0}; + Void::Pool::ObjectPool::Ptr retained_a; + Void::Pool::ObjectPool::Ptr retained_b; + + { + Void::Pool::ObjectPool 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 dtors{0}; + Void::Pool::ObjectPool 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 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 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 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 dtors{0}; + Void::Pool::FixedPool 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}); +} diff --git a/tests/standalone/Containers/Ring.cpp b/tests/standalone/Containers/Ring.cpp index e6945ae..68154a0 100644 --- a/tests/standalone/Containers/Ring.cpp +++ b/tests/standalone/Containers/Ring.cpp @@ -2,8 +2,11 @@ #include #include +#include +#include #include #include +#include #include // ── SpscRing ────────────────────────────────────────────────────────────────── @@ -144,3 +147,173 @@ Void::Testing::Test mpsc_two_producers_one_consumer() p1.join(); p2.join(); consumer.join(); Void::Testing::expect_eq(total.load(), N * 3); // N×1 + N×2 = 3N } + +namespace +{ + struct CountedItem + { + int value{0}; + std::atomic* dtors{nullptr}; + + CountedItem(int v, std::atomic* 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* entered_move{nullptr}; + std::atomic* release_move{nullptr}; + + DelayedMoveItem() noexcept = default; + DelayedMoveItem(int v, std::atomic* entered, std::atomic* 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 spsc_dtors{0}; + { + Void::Ring::SpscRing 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 mpsc_dtors{0}; + { + Void::Ring::MpscRing 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 ring; + std::atomic entered{false}; + std::atomic 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 ring; + constexpr int kProducers = 4; + constexpr std::uint64_t kPerProducer = 200; + std::vector 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(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(p) << 32) | i; + } + } + Void::Testing::expect_eq(xor_sum, expected_xor); +}