Files
Library/include/Void/Memory/Arena.hpp
T

399 lines
13 KiB
C++

#pragma once
#include <Void/Core/CheckedBits.hpp>
#include <Void/Memory/Resource.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <limits>
#include <memory>
#include <memory_resource>
#include <new>
#include <optional>
#include <span>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::Memory
{
/// Bounded bump arena supporting fixed-buffer and geometrically growing slab
/// modes, generation-checked checkpoints, and scoped typed destruction.
class Arena
{
public:
static constexpr std::size_t kDefaultSlabBytes = 64 * 1024;
static constexpr std::size_t kMaxSlabBytes = 1024 * 1024;
static constexpr std::size_t kDefaultMaxBytes = 16 * 1024 * 1024;
struct Checkpoint {
const Arena* owner{nullptr};
std::uint64_t generation{0};
std::size_t slab_index{0};
std::size_t offset{0};
std::size_t requested_live{0};
};
class TypedScope
{
public:
static constexpr std::size_t kDefaultMaxRegistrations = 4096;
explicit TypedScope(
Arena& arena,
std::size_t max_registrations = kDefaultMaxRegistrations) noexcept
: arena_(&arena), max_registrations_(max_registrations)
{
++arena_->active_scopes_;
}
TypedScope(const TypedScope&) = delete;
TypedScope& operator=(const TypedScope&) = delete;
TypedScope(TypedScope&&) = delete;
TypedScope& operator=(TypedScope&&) = delete;
~TypedScope() noexcept
{
for (auto it = entries_.rbegin(); it != entries_.rend(); ++it) {
it->destroy(it->ptr);
}
--arena_->active_scopes_;
}
template <class T, class... Args>
[[nodiscard]] std::expected<T*, AllocationError> emplace(Args&&... args)
{
if (entries_.size() >= max_registrations_) {
return std::unexpected{AllocationError::exhausted};
}
if constexpr (!std::is_trivially_destructible_v<T>) {
try {
entries_.reserve(entries_.size() + 1);
} catch (...) {
return std::unexpected{AllocationError::upstream_failure};
}
}
auto mem = arena_->try_allocate(sizeof(T), alignof(T));
if (!mem) {
return std::unexpected{mem.error()};
}
T* obj = ::new (*mem) T(std::forward<Args>(args)...);
if constexpr (!std::is_trivially_destructible_v<T>) {
entries_.push_back(
DestructorEntry{obj, [](void* p) noexcept {
static_cast<T*>(p)->~T();
}});
}
return obj;
}
[[nodiscard]] std::size_t registered_count() const noexcept
{
return entries_.size();
}
private:
struct DestructorEntry {
void* ptr;
void (*destroy)(void*) noexcept;
};
Arena* arena_;
std::size_t max_registrations_;
std::vector<DestructorEntry> entries_;
};
/// Fixed-buffer mode: never allocates from upstream.
explicit Arena(std::span<std::byte> fixed_buffer) noexcept
: fixed_mode_(true),
maximum_bytes_(fixed_buffer.size()),
initial_slab_bytes_(fixed_buffer.size()),
upstream_(nullptr)
{
if (!fixed_buffer.empty()) {
slabs_.push_back(Slab{fixed_buffer.data(), fixed_buffer.size(),
alignof(std::max_align_t), 0, false});
stats_.committed_live = fixed_buffer.size();
stats_.peak_committed = fixed_buffer.size();
}
}
/// Growing-slab mode using an upstream PMR resource (must outlive *this).
explicit Arena(
std::size_t maximum_bytes = kDefaultMaxBytes,
std::size_t initial_slab_bytes = kDefaultSlabBytes,
std::pmr::memory_resource& upstream =
*std::pmr::get_default_resource()) noexcept
: fixed_mode_(false),
maximum_bytes_(maximum_bytes),
initial_slab_bytes_(
std::max<std::size_t>(initial_slab_bytes, 64)),
upstream_(&upstream)
{
}
/// Initial caller buffer + growing upstream slab mode.
Arena(std::span<std::byte> initial_buffer, std::size_t maximum_bytes,
std::pmr::memory_resource& upstream =
*std::pmr::get_default_resource()) noexcept
: fixed_mode_(false),
maximum_bytes_(std::max(maximum_bytes, initial_buffer.size())),
initial_slab_bytes_(kDefaultSlabBytes),
upstream_(&upstream)
{
if (!initial_buffer.empty()) {
slabs_.push_back(Slab{initial_buffer.data(), initial_buffer.size(),
alignof(std::max_align_t), 0, false});
stats_.committed_live = initial_buffer.size();
stats_.peak_committed = initial_buffer.size();
}
}
Arena(const Arena&) = delete;
Arena& operator=(const Arena&) = delete;
Arena(Arena&&) = delete;
Arena& operator=(Arena&&) = delete;
~Arena() noexcept
{
for (const auto& s : slabs_) {
if (s.owned && upstream_ != nullptr) {
upstream_->deallocate(s.data, s.capacity, s.alignment);
}
}
}
[[nodiscard]] std::expected<void*, AllocationError>
try_allocate(std::size_t bytes,
std::size_t alignment = alignof(std::max_align_t)) noexcept
{
if (!is_valid_alignment(alignment)) {
++stats_.failures;
return std::unexpected{AllocationError::invalid_alignment};
}
// Zero-byte allocation reserves one addressable byte explicitly.
const std::size_t effective = (bytes == 0) ? 1 : bytes;
if (effective > std::numeric_limits<std::size_t>::max() -
stats_.requested_live) {
++stats_.failures;
return std::unexpected{AllocationError::size_overflow};
}
if (effective > maximum_bytes_) {
++stats_.failures;
return std::unexpected{AllocationError::exhausted};
}
// Try active slab and any already-retained empty slabs after rewind.
for (std::size_t i = active_slab_; i < slabs_.size(); ++i) {
if (auto ptr = try_allocate_in_slab(slabs_[i], effective, alignment)) {
active_slab_ = i;
record_alloc(effective);
return *ptr;
}
}
if (fixed_mode_ || upstream_ == nullptr) {
++stats_.failures;
return std::unexpected{AllocationError::exhausted};
}
const std::size_t slab_align =
std::max(alignment, alignof(std::max_align_t));
if (stats_.committed_live >= maximum_bytes_) {
++stats_.failures;
return std::unexpected{AllocationError::exhausted};
}
const std::size_t remaining_budget =
maximum_bytes_ - stats_.committed_live;
if (effective > remaining_budget) {
++stats_.failures;
return std::unexpected{AllocationError::exhausted};
}
std::size_t next_cap = initial_slab_bytes_;
if (!slabs_.empty()) {
const std::size_t prev = slabs_.back().capacity;
const std::size_t doubled =
prev <= kMaxSlabBytes / 2 ? prev * 2 : kMaxSlabBytes;
next_cap = std::max(initial_slab_bytes_,
std::min(kMaxSlabBytes, doubled));
}
next_cap = std::max(next_cap, effective);
next_cap = std::min(next_cap, remaining_budget);
void* raw = nullptr;
try {
raw = upstream_->allocate(next_cap, slab_align);
} catch (...) {
++stats_.failures;
return std::unexpected{AllocationError::upstream_failure};
}
try {
slabs_.push_back(Slab{static_cast<std::byte*>(raw), next_cap,
slab_align, 0, true});
} catch (...) {
upstream_->deallocate(raw, next_cap, slab_align);
++stats_.failures;
return std::unexpected{AllocationError::upstream_failure};
}
stats_.committed_live += next_cap;
stats_.peak_committed =
std::max(stats_.peak_committed, stats_.committed_live);
active_slab_ = slabs_.size() - 1;
auto ptr = try_allocate_in_slab(slabs_[active_slab_], effective,
alignment);
if (!ptr) {
++stats_.failures;
return std::unexpected{AllocationError::exhausted};
}
record_alloc(effective);
return *ptr;
}
[[nodiscard]] Checkpoint checkpoint() const noexcept
{
const std::size_t off =
slabs_.empty() ? 0 : slabs_[active_slab_].offset;
return Checkpoint{this, generation_, active_slab_, off,
stats_.requested_live};
}
[[nodiscard]] std::expected<void, AllocationError>
rewind(const Checkpoint& cp) noexcept
{
if (active_scopes_ > 0) {
return std::unexpected{AllocationError::live_allocations};
}
if (cp.owner != this || cp.generation != generation_) {
return std::unexpected{AllocationError::invalid_checkpoint};
}
if (slabs_.empty()) {
if (cp.slab_index != 0 || cp.offset != 0 ||
cp.requested_live != 0) {
return std::unexpected{AllocationError::invalid_checkpoint};
}
return {};
}
if (cp.slab_index > active_slab_ ||
cp.slab_index >= slabs_.size() ||
cp.offset > slabs_[cp.slab_index].capacity ||
(cp.slab_index == active_slab_ &&
cp.offset > slabs_[active_slab_].offset)) {
return std::unexpected{AllocationError::invalid_checkpoint};
}
for (std::size_t i = cp.slab_index + 1; i < slabs_.size(); ++i) {
slabs_[i].offset = 0;
}
slabs_[cp.slab_index].offset = cp.offset;
active_slab_ = cp.slab_index;
stats_.requested_live = cp.requested_live;
return {};
}
[[nodiscard]] std::expected<void, AllocationError> reset() noexcept
{
if (active_scopes_ > 0) {
return std::unexpected{AllocationError::live_allocations};
}
for (auto& s : slabs_) {
s.offset = 0;
}
active_slab_ = 0;
stats_.requested_live = 0;
++generation_;
return {};
}
[[nodiscard]] ResourceStats stats() const noexcept { return stats_; }
[[nodiscard]] std::uint64_t generation() const noexcept
{
return generation_;
}
private:
struct Slab {
std::byte* data;
std::size_t capacity;
std::size_t alignment;
std::size_t offset;
bool owned;
};
static std::optional<void*>
try_allocate_in_slab(Slab& s, std::size_t bytes,
std::size_t alignment) noexcept
{
const std::uintptr_t base_addr =
reinterpret_cast<std::uintptr_t>(s.data) + s.offset;
const auto aligned = Void::Bits::checked_align_up(
base_addr, static_cast<std::uintptr_t>(alignment));
if (!aligned) {
return std::nullopt;
}
const std::size_t pad = static_cast<std::size_t>(*aligned - base_addr);
const std::size_t rem = s.capacity - s.offset;
if (pad > rem || bytes > rem - pad) {
return std::nullopt;
}
s.offset += pad + bytes;
return reinterpret_cast<void*>(*aligned);
}
void record_alloc(std::size_t effective) noexcept
{
stats_.requested_live += effective;
stats_.peak_requested =
std::max(stats_.peak_requested, stats_.requested_live);
++stats_.allocations;
}
bool fixed_mode_;
std::size_t maximum_bytes_;
std::size_t initial_slab_bytes_;
std::pmr::memory_resource* upstream_;
std::vector<Slab> slabs_;
std::size_t active_slab_{0};
std::uint64_t generation_{1};
std::size_t active_scopes_{0};
ResourceStats stats_{};
};
/// PMR memory_resource adapter forwarding allocate calls to a borrowed Arena.
class ArenaResource final : public std::pmr::memory_resource
{
public:
explicit ArenaResource(Arena& arena) noexcept : arena_(&arena) {}
private:
void* do_allocate(std::size_t bytes, std::size_t alignment) override
{
auto res = arena_->try_allocate(bytes, alignment);
if (!res) {
throw std::bad_alloc{};
}
return *res;
}
void do_deallocate(void* /*p*/, std::size_t /*bytes*/,
std::size_t /*alignment*/) override
{
// Arena reclaims on rewind()/reset()/destruction.
}
bool do_is_equal(
const std::pmr::memory_resource& other) const noexcept override
{
return this == &other;
}
Arena* arena_;
};
} // namespace Void::Memory