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
|
||||
|
||||
#include <Void/Memory/Resource.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <memory_resource>
|
||||
#include <new>
|
||||
#include <span>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::BufferPool
|
||||
{
|
||||
|
||||
// ── BufferPool<T>
|
||||
// ───────────────────────────────────────────────────────────── A pool of
|
||||
// reusable, variable-length buffers of T — e.g. audio sample blocks (int16
|
||||
// / float). Distinct from Containers/Pool.hpp's ObjectPool, which pools
|
||||
// fixed-size *objects*: this pools backing storage sized by request.
|
||||
//
|
||||
// acquire(n) hands back a Buffer of logical length n backed by capacity
|
||||
// rounded up to the next power-of-two size class; on drop the storage
|
||||
// returns to the pool's bucket for that size class, so a later acquire of
|
||||
// the same class reuses it with no reallocation.
|
||||
//
|
||||
// Not thread-safe — guard externally if shared.
|
||||
enum class BufferPoolError : std::uint8_t
|
||||
{
|
||||
request_too_large,
|
||||
budget_exceeded,
|
||||
allocation_failed,
|
||||
size_overflow
|
||||
};
|
||||
|
||||
template <typename T> class BufferPool
|
||||
{
|
||||
public:
|
||||
// ── BufferPool<T> ─────────────────────────────────────────────────────────────
|
||||
// A pool of reusable, variable-length buffers of T with stationary shared state,
|
||||
// O(1) power-of-two bucket lists, explicit PMR upstream resource support, and
|
||||
// bounded request/idle/total byte limits.
|
||||
|
||||
BufferPool() = default;
|
||||
template <typename T> class BufferPool
|
||||
{
|
||||
public:
|
||||
struct Limits
|
||||
{
|
||||
std::size_t max_request_bytes = 1024 * 1024;
|
||||
std::size_t max_idle_bytes = 16 * 1024 * 1024;
|
||||
std::size_t max_total_bytes = 64 * 1024 * 1024;
|
||||
};
|
||||
|
||||
BufferPool(const BufferPool&) = delete;
|
||||
BufferPool& operator=(const BufferPool&) = delete;
|
||||
BufferPool(BufferPool&&) = default;
|
||||
BufferPool& operator=(BufferPool&&) = default;
|
||||
struct Stats
|
||||
{
|
||||
std::uint64_t allocations = 0; // fresh storage allocated
|
||||
std::uint64_t reuses = 0; // requests served from a bucket
|
||||
std::size_t pooled = 0; // buffers currently idle in buckets
|
||||
std::size_t idle_bytes = 0;
|
||||
std::size_t checked_out_bytes = 0;
|
||||
std::size_t total_bytes = 0;
|
||||
std::uint64_t dropped_on_return = 0; // released directly to upstream
|
||||
};
|
||||
|
||||
struct Stats {
|
||||
std::uint64_t allocations = 0; // fresh storage allocated
|
||||
std::uint64_t reuses = 0; // requests served from a bucket
|
||||
std::size_t pooled = 0; // buffers currently idle in buckets
|
||||
};
|
||||
private:
|
||||
struct Node
|
||||
{
|
||||
Node* next{nullptr};
|
||||
std::size_t cls{0};
|
||||
std::size_t payload_bytes{0};
|
||||
std::size_t total_alloc_bytes{0};
|
||||
std::size_t bucket_idx{0};
|
||||
};
|
||||
|
||||
// An owning view returned by acquire(); recycles its storage on
|
||||
// drop.
|
||||
class Buffer
|
||||
{
|
||||
public:
|
||||
static constexpr std::size_t kBlockAlign =
|
||||
(alignof(Node) > alignof(T)) ? alignof(Node) : alignof(T);
|
||||
static constexpr std::size_t kDataOffset =
|
||||
((sizeof(Node) + alignof(T) - 1) / alignof(T)) * alignof(T);
|
||||
static constexpr std::size_t kNumBuckets = 65;
|
||||
|
||||
Buffer() = default;
|
||||
static T* data_ptr(Node* node) noexcept
|
||||
{
|
||||
return reinterpret_cast<T*>(
|
||||
reinterpret_cast<std::byte*>(node) + kDataOffset);
|
||||
}
|
||||
|
||||
Buffer(const Buffer&) = delete;
|
||||
Buffer& operator=(const Buffer&) = delete;
|
||||
struct State
|
||||
{
|
||||
std::pmr::memory_resource* upstream;
|
||||
Limits limits;
|
||||
std::array<Node*, kNumBuckets> buckets{};
|
||||
std::uint64_t allocations{0};
|
||||
std::uint64_t reuses{0};
|
||||
std::size_t pooled{0};
|
||||
std::size_t idle_bytes{0};
|
||||
std::size_t checked_out_bytes{0};
|
||||
std::uint64_t dropped_on_return{0};
|
||||
bool owner_alive{true};
|
||||
|
||||
Buffer(Buffer&& other) noexcept
|
||||
: pool_{other.pool_},
|
||||
storage_{std::move(other.storage_)},
|
||||
size_{other.size_}
|
||||
{
|
||||
other.pool_ = nullptr;
|
||||
other.size_ = 0;
|
||||
}
|
||||
State(std::pmr::memory_resource* res, Limits lim) noexcept
|
||||
: upstream{res ? res : std::pmr::get_default_resource()},
|
||||
limits{lim}
|
||||
{
|
||||
}
|
||||
|
||||
Buffer& operator=(Buffer&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
recycle();
|
||||
pool_ = other.pool_;
|
||||
storage_ = std::move(other.storage_);
|
||||
size_ = other.size_;
|
||||
other.pool_ = nullptr;
|
||||
other.size_ = 0;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
~State() { shrink(); }
|
||||
|
||||
~Buffer() { recycle(); }
|
||||
void destroy_node(Node* node) noexcept
|
||||
{
|
||||
T* data = data_ptr(node);
|
||||
std::destroy_n(data, node->cls);
|
||||
const std::size_t bytes = node->total_alloc_bytes;
|
||||
std::destroy_at(node);
|
||||
upstream->deallocate(node, bytes, kBlockAlign);
|
||||
}
|
||||
|
||||
[[nodiscard]] T* data() noexcept { return storage_.data(); }
|
||||
[[nodiscard]] const T* data() const noexcept
|
||||
{
|
||||
return storage_.data();
|
||||
}
|
||||
[[nodiscard]] std::size_t size() const noexcept
|
||||
{
|
||||
return size_;
|
||||
}
|
||||
[[nodiscard]] bool empty() const noexcept
|
||||
{
|
||||
return size_ == 0;
|
||||
}
|
||||
// Backing capacity (the size class) — always >= size().
|
||||
[[nodiscard]] std::size_t capacity() const noexcept
|
||||
{
|
||||
return storage_.size();
|
||||
}
|
||||
void shrink() noexcept
|
||||
{
|
||||
for (Node*& head : buckets) {
|
||||
while (head) {
|
||||
Node* node = head;
|
||||
head = node->next;
|
||||
idle_bytes -= node->payload_bytes;
|
||||
--pooled;
|
||||
destroy_node(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] T& operator[](std::size_t i) noexcept
|
||||
{
|
||||
return storage_[i];
|
||||
}
|
||||
[[nodiscard]] const T&
|
||||
operator[](std::size_t i) const noexcept
|
||||
{
|
||||
return storage_[i];
|
||||
}
|
||||
void release(Node* node) noexcept
|
||||
{
|
||||
checked_out_bytes -= node->payload_bytes;
|
||||
const std::size_t b = node->payload_bytes;
|
||||
const bool can_retain =
|
||||
owner_alive &&
|
||||
b <= limits.max_idle_bytes &&
|
||||
idle_bytes <= limits.max_idle_bytes - b &&
|
||||
(checked_out_bytes + idle_bytes) <= limits.max_total_bytes - b;
|
||||
if (can_retain) {
|
||||
node->next = buckets[node->bucket_idx];
|
||||
buckets[node->bucket_idx] = node;
|
||||
++pooled;
|
||||
idle_bytes += b;
|
||||
} else {
|
||||
destroy_node(node);
|
||||
++dropped_on_return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
[[nodiscard]] T* begin() noexcept { return data(); }
|
||||
[[nodiscard]] T* end() noexcept { return data() + size_; }
|
||||
[[nodiscard]] const T* begin() const noexcept
|
||||
{
|
||||
return data();
|
||||
}
|
||||
[[nodiscard]] const T* end() const noexcept
|
||||
{
|
||||
return data() + size_;
|
||||
}
|
||||
public:
|
||||
BufferPool()
|
||||
: BufferPool(Limits{}, std::pmr::get_default_resource())
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] std::span<T> span() noexcept
|
||||
{
|
||||
return {data(), size_};
|
||||
}
|
||||
[[nodiscard]] std::span<const T> span() const noexcept
|
||||
{
|
||||
return {data(), size_};
|
||||
}
|
||||
explicit BufferPool(
|
||||
Limits limits,
|
||||
std::pmr::memory_resource* upstream = std::pmr::get_default_resource())
|
||||
: state_{std::make_shared<State>(upstream, limits)}
|
||||
{
|
||||
}
|
||||
|
||||
private:
|
||||
explicit BufferPool(
|
||||
Void::Memory::UnlimitedTag,
|
||||
std::pmr::memory_resource* upstream = std::pmr::get_default_resource())
|
||||
: state_{std::make_shared<State>(
|
||||
upstream,
|
||||
Limits{
|
||||
.max_request_bytes = std::numeric_limits<std::size_t>::max(),
|
||||
.max_idle_bytes = std::numeric_limits<std::size_t>::max(),
|
||||
.max_total_bytes = std::numeric_limits<std::size_t>::max()})}
|
||||
{
|
||||
}
|
||||
|
||||
friend class BufferPool;
|
||||
explicit BufferPool(
|
||||
std::pmr::memory_resource* upstream,
|
||||
Limits limits = {})
|
||||
: state_{std::make_shared<State>(upstream, limits)}
|
||||
{
|
||||
}
|
||||
|
||||
Buffer(BufferPool* pool, std::vector<T> storage,
|
||||
std::size_t n) noexcept
|
||||
: pool_{pool}, storage_{std::move(storage)}, size_{n}
|
||||
{
|
||||
}
|
||||
BufferPool(const BufferPool&) = delete;
|
||||
BufferPool& operator=(const BufferPool&) = delete;
|
||||
|
||||
void recycle() noexcept
|
||||
{
|
||||
if (pool_) {
|
||||
pool_->recycle(std::move(storage_));
|
||||
pool_ = nullptr;
|
||||
}
|
||||
}
|
||||
BufferPool(BufferPool&&) noexcept = default;
|
||||
|
||||
BufferPool* pool_ = nullptr;
|
||||
std::vector<T> storage_;
|
||||
std::size_t size_ = 0;
|
||||
};
|
||||
BufferPool& operator=(BufferPool&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
teardown();
|
||||
state_ = std::move(other.state_);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Hand out a buffer of logical length n (capacity rounded up to a
|
||||
// power of two), reusing pooled storage of that size class when
|
||||
// available.
|
||||
[[nodiscard]] Buffer acquire(std::size_t n)
|
||||
{
|
||||
const std::size_t cls = size_class(n);
|
||||
std::vector<T> storage;
|
||||
auto bucket = free_.find(cls);
|
||||
if (bucket != free_.end() && !bucket->second.empty()) {
|
||||
storage = std::move(bucket->second.back());
|
||||
bucket->second.pop_back();
|
||||
++reuses_;
|
||||
} else {
|
||||
storage.resize(cls);
|
||||
++allocations_;
|
||||
}
|
||||
return Buffer{this, std::move(storage), n};
|
||||
}
|
||||
~BufferPool() { teardown(); }
|
||||
|
||||
[[nodiscard]] Stats stats() const
|
||||
{
|
||||
std::size_t pooled = 0;
|
||||
for (const auto& [cls, bucket] : free_) {
|
||||
pooled += bucket.size();
|
||||
}
|
||||
return Stats{allocations_, reuses_, pooled};
|
||||
}
|
||||
// Owning view returned by acquire()/try_acquire(); recycles cleanly on drop.
|
||||
class Buffer
|
||||
{
|
||||
public:
|
||||
Buffer() = default;
|
||||
Buffer(const Buffer&) = delete;
|
||||
Buffer& operator=(const Buffer&) = delete;
|
||||
|
||||
// Drop all pooled (idle) storage. Outstanding Buffers are
|
||||
// unaffected.
|
||||
void shrink() noexcept { free_.clear(); }
|
||||
Buffer(Buffer&& other) noexcept
|
||||
: state_{std::move(other.state_)},
|
||||
node_{std::exchange(other.node_, nullptr)},
|
||||
size_{std::exchange(other.size_, 0)}
|
||||
{
|
||||
}
|
||||
|
||||
private:
|
||||
Buffer& operator=(Buffer&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
recycle();
|
||||
state_ = std::move(other.state_);
|
||||
node_ = std::exchange(other.node_, nullptr);
|
||||
size_ = std::exchange(other.size_, 0);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
static std::size_t size_class(std::size_t n) noexcept
|
||||
{
|
||||
return n == 0 ? 0 : std::bit_ceil(n);
|
||||
}
|
||||
~Buffer() { recycle(); }
|
||||
|
||||
void recycle(std::vector<T> storage)
|
||||
{
|
||||
if (storage.empty()) {
|
||||
return;
|
||||
}
|
||||
free_[storage.size()].push_back(std::move(storage));
|
||||
}
|
||||
[[nodiscard]] T* data() noexcept
|
||||
{
|
||||
return node_ ? data_ptr(node_) : nullptr;
|
||||
}
|
||||
[[nodiscard]] const T* data() const noexcept
|
||||
{
|
||||
return node_ ? data_ptr(node_) : nullptr;
|
||||
}
|
||||
[[nodiscard]] std::size_t size() const noexcept { return size_; }
|
||||
[[nodiscard]] bool empty() const noexcept { return size_ == 0; }
|
||||
[[nodiscard]] std::size_t capacity() const noexcept
|
||||
{
|
||||
return node_ ? node_->cls : 0;
|
||||
}
|
||||
|
||||
std::unordered_map<std::size_t, std::vector<std::vector<T>>> free_;
|
||||
std::uint64_t allocations_ = 0;
|
||||
std::uint64_t reuses_ = 0;
|
||||
};
|
||||
[[nodiscard]] T& operator[](std::size_t i) noexcept { return data()[i]; }
|
||||
[[nodiscard]] const T& operator[](std::size_t i) const noexcept
|
||||
{
|
||||
return data()[i];
|
||||
}
|
||||
|
||||
[[nodiscard]] T* begin() noexcept { return data(); }
|
||||
[[nodiscard]] T* end() noexcept { return data() ? data() + size_ : nullptr; }
|
||||
[[nodiscard]] const T* begin() const noexcept { return data(); }
|
||||
[[nodiscard]] const T* end() const noexcept
|
||||
{
|
||||
return data() ? data() + size_ : nullptr;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::span<T> span() noexcept { return {data(), size_}; }
|
||||
[[nodiscard]] std::span<const T> span() const noexcept
|
||||
{
|
||||
return {data(), size_};
|
||||
}
|
||||
|
||||
private:
|
||||
friend class BufferPool;
|
||||
|
||||
Buffer(std::shared_ptr<State> state, Node* node, std::size_t n) noexcept
|
||||
: state_{std::move(state)}, node_{node}, size_{n}
|
||||
{
|
||||
}
|
||||
|
||||
void recycle() noexcept
|
||||
{
|
||||
if (node_ && state_) {
|
||||
state_->release(node_);
|
||||
}
|
||||
node_ = nullptr;
|
||||
size_ = 0;
|
||||
state_.reset();
|
||||
}
|
||||
|
||||
std::shared_ptr<State> state_{};
|
||||
Node* node_{nullptr};
|
||||
std::size_t size_{0};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::expected<Buffer, BufferPoolError>
|
||||
try_acquire(std::size_t n)
|
||||
{
|
||||
if (!state_) {
|
||||
return std::unexpected{BufferPoolError::budget_exceeded};
|
||||
}
|
||||
if (n == 0) {
|
||||
return Buffer{};
|
||||
}
|
||||
|
||||
constexpr std::size_t kMaxSize = std::numeric_limits<std::size_t>::max();
|
||||
constexpr std::size_t kMaxPow2 =
|
||||
std::size_t{1} << (std::numeric_limits<std::size_t>::digits - 1);
|
||||
if (n > kMaxPow2) {
|
||||
return std::unexpected{BufferPoolError::size_overflow};
|
||||
}
|
||||
const std::size_t cls = std::bit_ceil(n);
|
||||
if (cls > (kMaxSize / sizeof(T))) {
|
||||
return std::unexpected{BufferPoolError::size_overflow};
|
||||
}
|
||||
const std::size_t payload_bytes = cls * sizeof(T);
|
||||
if (payload_bytes > state_->limits.max_request_bytes) {
|
||||
return std::unexpected{BufferPoolError::request_too_large};
|
||||
}
|
||||
if (payload_bytes > (kMaxSize - kDataOffset)) {
|
||||
return std::unexpected{BufferPoolError::size_overflow};
|
||||
}
|
||||
|
||||
const std::size_t bucket_idx =
|
||||
static_cast<std::size_t>(std::countr_zero(cls));
|
||||
if (Node* reused = state_->buckets[bucket_idx]) {
|
||||
state_->buckets[bucket_idx] = reused->next;
|
||||
reused->next = nullptr;
|
||||
--state_->pooled;
|
||||
state_->idle_bytes -= reused->payload_bytes;
|
||||
state_->checked_out_bytes += reused->payload_bytes;
|
||||
++state_->reuses;
|
||||
return Buffer{state_, reused, n};
|
||||
}
|
||||
|
||||
const std::size_t active_bytes =
|
||||
state_->checked_out_bytes + state_->idle_bytes;
|
||||
if (payload_bytes > state_->limits.max_total_bytes ||
|
||||
active_bytes > state_->limits.max_total_bytes - payload_bytes) {
|
||||
return std::unexpected{BufferPoolError::budget_exceeded};
|
||||
}
|
||||
|
||||
const std::size_t total_alloc_bytes = kDataOffset + payload_bytes;
|
||||
void* raw = nullptr;
|
||||
try {
|
||||
raw = state_->upstream->allocate(total_alloc_bytes, kBlockAlign);
|
||||
} catch (...) {
|
||||
return std::unexpected{BufferPoolError::allocation_failed};
|
||||
}
|
||||
if (!raw) {
|
||||
return std::unexpected{BufferPoolError::allocation_failed};
|
||||
}
|
||||
|
||||
Node* node = std::construct_at(static_cast<Node*>(raw));
|
||||
node->cls = cls;
|
||||
node->payload_bytes = payload_bytes;
|
||||
node->total_alloc_bytes = total_alloc_bytes;
|
||||
node->bucket_idx = bucket_idx;
|
||||
|
||||
try {
|
||||
std::uninitialized_value_construct_n(data_ptr(node), cls);
|
||||
} catch (...) {
|
||||
std::destroy_at(node);
|
||||
state_->upstream->deallocate(raw, total_alloc_bytes, kBlockAlign);
|
||||
throw;
|
||||
}
|
||||
|
||||
state_->checked_out_bytes += payload_bytes;
|
||||
++state_->allocations;
|
||||
return Buffer{state_, node, n};
|
||||
}
|
||||
|
||||
[[nodiscard]] Buffer acquire(std::size_t n)
|
||||
{
|
||||
auto r = try_acquire(n);
|
||||
if (!r) {
|
||||
throw std::bad_alloc{};
|
||||
}
|
||||
return std::move(*r);
|
||||
}
|
||||
|
||||
[[nodiscard]] Stats stats() const noexcept
|
||||
{
|
||||
if (!state_) {
|
||||
return Stats{};
|
||||
}
|
||||
return Stats{
|
||||
state_->allocations,
|
||||
state_->reuses,
|
||||
state_->pooled,
|
||||
state_->idle_bytes,
|
||||
state_->checked_out_bytes,
|
||||
state_->idle_bytes + state_->checked_out_bytes,
|
||||
state_->dropped_on_return};
|
||||
}
|
||||
|
||||
[[nodiscard]] Limits limits() const noexcept
|
||||
{
|
||||
return state_ ? state_->limits : Limits{};
|
||||
}
|
||||
|
||||
// Drop all pooled (idle) storage. Outstanding Buffers are unaffected.
|
||||
void shrink() noexcept
|
||||
{
|
||||
if (state_) {
|
||||
state_->shrink();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void teardown() noexcept
|
||||
{
|
||||
if (state_) {
|
||||
state_->owner_alive = false;
|
||||
state_->shrink();
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<State> state_;
|
||||
};
|
||||
|
||||
} // namespace Void::BufferPool
|
||||
Reference in new issue
Block a user