Files
Library/include/Void/Containers/BufferPool.hpp
T
faumarayandClaude Opus 4.8 80293ee56f Add async/resilience/reflection primitives + FSM v2 rewrite
A round of new universal capabilities (all generic — templated/reflection
based, no app coupling), verified by the test suite (1103 passing):

Data reflection:
- Reflect.hpp now (de)serializes chrono::duration, chrono::time_point,
  std::variant (tagged), std::array, and non-string-keyed std::map;
  Meta.hpp gains is_time_point_v et al.

Async:
- EventBus gains Mode::Async (worker-thread dispatch + flush()).
- ThreadPool gains a bounded queue, try_submit(), and rejection stats.

New modules / containers:
- Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker,
  ResourceMonitor.
- Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V>
  (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats).
- System: process/CPU/memory metrics (Metrics.hpp) and a streaming
  Process API.

Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions,
history states, deferred events), Configuration/Logging reflection
helpers, and the accompanying test suites.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:45:16 +03:00

204 lines
5.1 KiB
C++

#pragma once
#include <bit>
#include <cstddef>
#include <cstdint>
#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.
template <typename T> class BufferPool
{
public:
BufferPool() = default;
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
};
// An owning view returned by acquire(); recycles its storage on
// drop.
class Buffer
{
public:
Buffer() = default;
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
Buffer(Buffer&& other) noexcept
: pool_{other.pool_},
storage_{std::move(other.storage_)},
size_{other.size_}
{
other.pool_ = nullptr;
other.size_ = 0;
}
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;
}
~Buffer() { recycle(); }
[[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();
}
[[nodiscard]] T& operator[](std::size_t i) noexcept
{
return storage_[i];
}
[[nodiscard]] const T&
operator[](std::size_t i) const noexcept
{
return storage_[i];
}
[[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_;
}
[[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(BufferPool* pool, std::vector<T> storage,
std::size_t n) noexcept
: pool_{pool}, storage_{std::move(storage)}, size_{n}
{
}
void recycle() noexcept
{
if (pool_) {
pool_->recycle(std::move(storage_));
pool_ = nullptr;
}
}
BufferPool* pool_ = nullptr;
std::vector<T> storage_;
std::size_t size_ = 0;
};
// 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};
}
[[nodiscard]] Stats stats() const
{
std::size_t pooled = 0;
for (const auto& [cls, bucket] : free_) {
pooled += bucket.size();
}
return Stats{allocations_, reuses_, pooled};
}
// Drop all pooled (idle) storage. Outstanding Buffers are
// unaffected.
void shrink() noexcept { free_.clear(); }
private:
static std::size_t size_class(std::size_t n) noexcept
{
return n == 0 ? 0 : std::bit_ceil(n);
}
void recycle(std::vector<T> storage)
{
if (storage.empty()) {
return;
}
free_[storage.size()].push_back(std::move(storage));
}
std::unordered_map<std::size_t, std::vector<std::vector<T>>> free_;
std::uint64_t allocations_ = 0;
std::uint64_t reuses_ = 0;
};
} // namespace Void::BufferPool