#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::BufferPool { enum class BufferPoolError : std::uint8_t { request_too_large, budget_exceeded, allocation_failed, size_overflow }; // ── 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. 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; }; 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 }; 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}; }; 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; static T* data_ptr(Node* node) noexcept { return reinterpret_cast( reinterpret_cast(node) + kDataOffset); } 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}; State(std::pmr::memory_resource* res, Limits lim) noexcept : upstream{res ? res : std::pmr::get_default_resource()}, limits{lim} { } ~State() { shrink(); } 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); } void shrink() noexcept { for (Node*& head : buckets) { while (head) { Node* node = head; head = node->next; idle_bytes -= node->payload_bytes; --pooled; destroy_node(node); } } } 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; } } }; public: BufferPool() : BufferPool(Limits{}, std::pmr::get_default_resource()) { } explicit BufferPool( Limits limits, std::pmr::memory_resource* upstream = std::pmr::get_default_resource()) : state_{std::make_shared(upstream, limits)} { } 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()})} { } explicit BufferPool( std::pmr::memory_resource* upstream, Limits limits = {}) : state_{std::make_shared(upstream, limits)} { } BufferPool(const BufferPool&) = delete; BufferPool& operator=(const BufferPool&) = delete; BufferPool(BufferPool&&) noexcept = default; BufferPool& operator=(BufferPool&& other) noexcept { if (this != &other) { teardown(); state_ = std::move(other.state_); } return *this; } ~BufferPool() { teardown(); } // 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; Buffer(Buffer&& other) noexcept : state_{std::move(other.state_)}, node_{std::exchange(other.node_, nullptr)}, size_{std::exchange(other.size_, 0)} { } 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; } ~Buffer() { recycle(); } [[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; } [[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