feat(Memory): add Memory subsystem with BudgetResource, Arena, and BlockPool (S-MEMORY-02..04)

This commit is contained in:
faumaray committed 2026-11-24 02:49:28 +03:00
1 parent 4227348051
commit 4d48f2a8f2
11 files changed
+1306

No files matched your search

+398
View File
@@ -0,0 +1,398 @@
#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
+288
View File
@@ -0,0 +1,288 @@
#pragma once
#include <Void/Core/CheckedBits.hpp>
#include <Void/Memory/Resource.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <expected>
#include <limits>
#include <memory_resource>
#include <mutex>
#include <vector>
namespace Void::Memory
{
/// Bounded fixed-size block allocator using per-slab intrusive free lists.
/// Recycling via `deallocate` performs zero heap allocations and is noexcept.
class BlockPool
{
public:
static constexpr std::size_t kDefaultMaxBlocks = 4096;
static constexpr std::size_t kDefaultMaxCommittedBytes = 16 * 1024 * 1024;
static constexpr std::size_t kDefaultBlocksPerSlab = 64;
explicit BlockPool(
std::size_t block_size,
std::size_t block_alignment = alignof(std::max_align_t),
std::size_t max_blocks = kDefaultMaxBlocks,
std::size_t max_committed_bytes = kDefaultMaxCommittedBytes,
std::size_t blocks_per_slab = kDefaultBlocksPerSlab,
std::pmr::memory_resource& upstream =
*std::pmr::get_default_resource())
: max_blocks_(max_blocks),
max_committed_bytes_(max_committed_bytes),
blocks_per_slab_(std::max<std::size_t>(blocks_per_slab, 1)),
upstream_(&upstream)
{
const std::size_t eff_align =
is_valid_alignment(block_alignment) ? block_alignment
: alignof(std::max_align_t);
valid_config_ = is_valid_alignment(block_alignment);
const std::size_t min_size = std::max(block_size, sizeof(void*));
const auto aligned = Void::Bits::checked_align_up(min_size, eff_align);
if (!aligned) {
valid_config_ = false;
stride_ = min_size;
} else {
stride_ = *aligned;
}
slab_align_ = std::max(eff_align, alignof(std::max_align_t));
}
BlockPool(const BlockPool&) = delete;
BlockPool& operator=(const BlockPool&) = delete;
BlockPool(BlockPool&&) = delete;
BlockPool& operator=(BlockPool&&) = delete;
~BlockPool() noexcept
{
for (const auto& s : slabs_) {
upstream_->deallocate(s.data, s.total_bytes, slab_align_);
}
}
[[nodiscard]] std::expected<void*, AllocationError> try_allocate() noexcept
{
if (!valid_config_) {
++stats_.failures;
return std::unexpected{AllocationError::invalid_alignment};
}
if (total_live_blocks_ >= max_blocks_) {
++stats_.failures;
return std::unexpected{AllocationError::exhausted};
}
for (auto& s : slabs_) {
if (s.free_head != nullptr) {
void* ptr = pop_free(s);
record_alloc();
return ptr;
}
}
if (total_capacity_blocks_ >= max_blocks_ ||
stats_.committed_live >= max_committed_bytes_) {
++stats_.failures;
return std::unexpected{AllocationError::exhausted};
}
const std::size_t remaining_blocks = max_blocks_ - total_capacity_blocks_;
std::size_t count = std::min(blocks_per_slab_, remaining_blocks);
const std::size_t remaining_bytes =
max_committed_bytes_ - stats_.committed_live;
const std::size_t max_by_bytes = remaining_bytes / stride_;
count = std::min(count, max_by_bytes);
if (count == 0) {
++stats_.failures;
return std::unexpected{AllocationError::exhausted};
}
if (count > std::numeric_limits<std::size_t>::max() / stride_) {
++stats_.failures;
return std::unexpected{AllocationError::size_overflow};
}
const std::size_t total_bytes = count * stride_;
void* raw = nullptr;
try {
raw = upstream_->allocate(total_bytes, slab_align_);
} catch (...) {
++stats_.failures;
return std::unexpected{AllocationError::upstream_failure};
}
auto* base = static_cast<std::byte*>(raw);
for (std::size_t i = 0; i + 1 < count; ++i) {
void* next_blk = base + (i + 1) * stride_;
std::memcpy(base + i * stride_, &next_blk, sizeof(void*));
}
void* null_next = nullptr;
std::memcpy(base + (count - 1) * stride_, &null_next, sizeof(void*));
try {
slabs_.push_back(Slab{base, total_bytes, count, 0, base});
} catch (...) {
upstream_->deallocate(raw, total_bytes, slab_align_);
++stats_.failures;
return std::unexpected{AllocationError::upstream_failure};
}
total_capacity_blocks_ += count;
stats_.committed_live += total_bytes;
stats_.peak_committed =
std::max(stats_.peak_committed, stats_.committed_live);
void* ptr = pop_free(slabs_.back());
record_alloc();
return ptr;
}
void deallocate(void* ptr) noexcept
{
if (ptr == nullptr) {
return;
}
const std::uintptr_t addr = reinterpret_cast<std::uintptr_t>(ptr);
for (auto& s : slabs_) {
const std::uintptr_t lo = reinterpret_cast<std::uintptr_t>(s.data);
const std::uintptr_t hi = lo + s.total_bytes;
if (addr >= lo && addr < hi) {
std::memcpy(ptr, &s.free_head, sizeof(void*));
s.free_head = ptr;
--s.live_count;
--total_live_blocks_;
stats_.requested_live -= stride_;
++stats_.deallocations;
return;
}
}
}
/// Release completely idle slabs back to upstream; never touches slabs
/// with live blocks. Returns the number of reclaimed bytes.
std::size_t trim_idle() noexcept
{
std::size_t reclaimed = 0;
std::size_t dst = 0;
for (std::size_t src = 0; src < slabs_.size(); ++src) {
Slab& s = slabs_[src];
if (s.live_count == 0) {
upstream_->deallocate(s.data, s.total_bytes, slab_align_);
total_capacity_blocks_ -= s.block_count;
stats_.committed_live -= s.total_bytes;
reclaimed += s.total_bytes;
} else {
if (dst != src) {
slabs_[dst] = s;
}
++dst;
}
}
slabs_.resize(dst);
return reclaimed;
}
[[nodiscard]] std::size_t block_stride() const noexcept { return stride_; }
[[nodiscard]] std::size_t live_blocks() const noexcept
{
return total_live_blocks_;
}
[[nodiscard]] std::size_t capacity_blocks() const noexcept
{
return total_capacity_blocks_;
}
[[nodiscard]] ResourceStats stats() const noexcept { return stats_; }
private:
struct Slab {
std::byte* data;
std::size_t total_bytes;
std::size_t block_count;
std::size_t live_count;
void* free_head;
};
static void* pop_free(Slab& s) noexcept
{
void* ptr = s.free_head;
void* next = nullptr;
std::memcpy(&next, ptr, sizeof(void*));
s.free_head = next;
++s.live_count;
return ptr;
}
void record_alloc() noexcept
{
++total_live_blocks_;
stats_.requested_live += stride_;
stats_.peak_requested =
std::max(stats_.peak_requested, stats_.requested_live);
++stats_.allocations;
}
bool valid_config_{true};
std::size_t stride_{0};
std::size_t slab_align_{alignof(std::max_align_t)};
std::size_t max_blocks_;
std::size_t max_committed_bytes_;
std::size_t blocks_per_slab_;
std::pmr::memory_resource* upstream_;
std::vector<Slab> slabs_;
std::size_t total_live_blocks_{0};
std::size_t total_capacity_blocks_{0};
ResourceStats stats_{};
};
/// Mutex-protected thread-safe wrapper over BlockPool.
class SynchronizedBlockPool
{
public:
explicit SynchronizedBlockPool(
std::size_t block_size,
std::size_t block_alignment = alignof(std::max_align_t),
std::size_t max_blocks = BlockPool::kDefaultMaxBlocks,
std::size_t max_committed_bytes =
BlockPool::kDefaultMaxCommittedBytes,
std::size_t blocks_per_slab = BlockPool::kDefaultBlocksPerSlab,
std::pmr::memory_resource& upstream =
*std::pmr::get_default_resource())
: inner_(block_size, block_alignment, max_blocks, max_committed_bytes,
blocks_per_slab, upstream)
{
}
[[nodiscard]] std::expected<void*, AllocationError> try_allocate() noexcept
{
std::lock_guard lock{mutex_};
return inner_.try_allocate();
}
void deallocate(void* ptr) noexcept
{
std::lock_guard lock{mutex_};
inner_.deallocate(ptr);
}
std::size_t trim_idle() noexcept
{
std::lock_guard lock{mutex_};
return inner_.trim_idle();
}
[[nodiscard]] ResourceStats stats() const noexcept
{
std::lock_guard lock{mutex_};
return inner_.stats();
}
private:
mutable std::mutex mutex_;
BlockPool inner_;
};
} // namespace Void::Memory
+171
View File
@@ -0,0 +1,171 @@
#pragma once
#include <Void/Memory/Resource.hpp>
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <limits>
#include <memory_resource>
#include <new>
namespace Void::Memory
{
/// Bounded, thread-safe PMR memory resource that enforces a byte budget atomically
/// before forwarding allocations to its upstream resource.
class BudgetResource final : public std::pmr::memory_resource
{
public:
explicit BudgetResource(
std::size_t byte_limit,
std::pmr::memory_resource& upstream =
*std::pmr::get_default_resource()) noexcept
: byte_limit_(byte_limit), unlimited_(false), upstream_(&upstream)
{
}
explicit BudgetResource(
UnlimitedTag,
std::pmr::memory_resource& upstream =
*std::pmr::get_default_resource()) noexcept
: byte_limit_(std::numeric_limits<std::size_t>::max()),
unlimited_(true),
upstream_(&upstream)
{
}
BudgetResource(const BudgetResource&) = delete;
BudgetResource& operator=(const BudgetResource&) = delete;
BudgetResource(BudgetResource&&) = delete;
BudgetResource& operator=(BudgetResource&&) = delete;
[[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)) {
failures_.fetch_add(1, std::memory_order_relaxed);
return std::unexpected{AllocationError::invalid_alignment};
}
if (!unlimited_ && bytes > byte_limit_) {
failures_.fetch_add(1, std::memory_order_relaxed);
return std::unexpected{AllocationError::exhausted};
}
std::size_t cur = committed_live_.load(std::memory_order_relaxed);
for (;;) {
if (bytes > std::numeric_limits<std::size_t>::max() - cur) {
failures_.fetch_add(1, std::memory_order_relaxed);
return std::unexpected{AllocationError::size_overflow};
}
const std::size_t next = cur + bytes;
if (!unlimited_ && next > byte_limit_) {
failures_.fetch_add(1, std::memory_order_relaxed);
return std::unexpected{AllocationError::exhausted};
}
if (committed_live_.compare_exchange_weak(
cur, next, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
break;
}
}
void* ptr = nullptr;
try {
ptr = upstream_->allocate(bytes, alignment);
} catch (...) {
committed_live_.fetch_sub(bytes, std::memory_order_release);
failures_.fetch_add(1, std::memory_order_relaxed);
return std::unexpected{AllocationError::upstream_failure};
}
const std::size_t live_req =
requested_live_.fetch_add(bytes, std::memory_order_relaxed) + bytes;
const std::size_t live_com =
committed_live_.load(std::memory_order_relaxed);
update_max(peak_requested_, live_req);
update_max(peak_committed_, live_com);
allocations_.fetch_add(1, std::memory_order_relaxed);
return ptr;
}
void deallocate_checked(
void* ptr, std::size_t bytes,
std::size_t alignment = alignof(std::max_align_t)) noexcept
{
upstream_->deallocate(ptr, bytes, alignment);
requested_live_.fetch_sub(bytes, std::memory_order_relaxed);
committed_live_.fetch_sub(bytes, std::memory_order_release);
deallocations_.fetch_add(1, std::memory_order_relaxed);
}
[[nodiscard]] ResourceStats stats() const noexcept
{
ResourceStats s;
s.requested_live = requested_live_.load(std::memory_order_acquire);
s.committed_live = committed_live_.load(std::memory_order_acquire);
s.peak_requested = peak_requested_.load(std::memory_order_acquire);
s.peak_committed = peak_committed_.load(std::memory_order_acquire);
s.allocations = allocations_.load(std::memory_order_relaxed);
s.deallocations = deallocations_.load(std::memory_order_relaxed);
s.failures = failures_.load(std::memory_order_relaxed);
return s;
}
[[nodiscard]] std::size_t byte_limit() const noexcept
{
return byte_limit_;
}
[[nodiscard]] bool is_unlimited() const noexcept { return unlimited_; }
private:
static void update_max(std::atomic<std::size_t>& target,
std::size_t candidate) noexcept
{
std::size_t cur = target.load(std::memory_order_relaxed);
while (candidate > cur &&
!target.compare_exchange_weak(cur, candidate,
std::memory_order_relaxed,
std::memory_order_relaxed)) {
}
}
void* do_allocate(std::size_t bytes, std::size_t alignment) override
{
auto res = 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
{
deallocate_checked(p, bytes, alignment);
}
bool do_is_equal(
const std::pmr::memory_resource& other) const noexcept override
{
return this == &other;
}
std::size_t byte_limit_;
bool unlimited_;
std::pmr::memory_resource* upstream_;
std::atomic<std::size_t> requested_live_{0};
std::atomic<std::size_t> committed_live_{0};
std::atomic<std::size_t> peak_requested_{0};
std::atomic<std::size_t> peak_committed_{0};
std::atomic<std::uint64_t> allocations_{0};
std::atomic<std::uint64_t> deallocations_{0};
std::atomic<std::uint64_t> failures_{0};
};
} // namespace Void::Memory
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <bit>
#include <cstddef>
#include <cstdint>
namespace Void::Memory
{
enum class AllocationError {
invalid_alignment,
size_overflow,
exhausted,
upstream_failure,
live_allocations,
invalid_checkpoint
};
struct UnlimitedTag {};
inline constexpr UnlimitedTag unlimited{};
struct ResourceStats {
std::size_t requested_live{0};
std::size_t committed_live{0};
std::size_t peak_requested{0};
std::size_t peak_committed{0};
std::uint64_t allocations{0};
std::uint64_t deallocations{0};
std::uint64_t failures{0};
};
[[nodiscard]] constexpr bool
is_valid_alignment(std::size_t alignment) noexcept
{
return alignment != 0 && std::has_single_bit(alignment);
}
} // namespace Void::Memory
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Memory
INTERNAL_DEPS Core
)
+5
View File
@@ -86,6 +86,11 @@ if(_has_core)
run_consumer(CoreOnly "${install_prefix}" "CoreOnly" ${_no_external_deps})
endif()
has_modules(_has_memory Memory Core)
if(_has_memory)
run_consumer(MemoryOnly "${install_prefix}" "MemoryOnly" ${_no_external_deps})
endif()
has_modules(_has_binary Binary)
if(_has_binary)
run_consumer(Binary "${install_prefix}" "Binary" ${_no_external_deps})
+10
View File
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(VoidMemoryOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Memory)
add_executable(void_memory_only_consumer main.cpp)
target_link_libraries(void_memory_only_consumer PRIVATE Void::Memory)
enable_testing()
add_test(NAME VoidMemoryOnlyConsumer COMMAND void_memory_only_consumer)
+19
View File
@@ -0,0 +1,19 @@
#include <Void/Memory/Arena.hpp>
#include <Void/Memory/BlockPool.hpp>
#include <Void/Memory/BudgetResource.hpp>
int main()
{
Void::Memory::BudgetResource budget{1024 * 1024};
Void::Memory::Arena arena{65536, 4096, budget};
Void::Memory::BlockPool pool{64, 16, 16, 4096, 8, budget};
auto mem = arena.try_allocate(128, 32);
auto blk = pool.try_allocate();
if (!mem || !blk) {
return 1;
}
pool.deallocate(*blk);
(void)pool.trim_idle();
return arena.reset().has_value() ? 0 : 1;
}
+124
View File
@@ -0,0 +1,124 @@
#include <Void/Memory/Arena.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <vector>
namespace
{
struct TrackedItem {
int id;
std::vector<int>* log;
TrackedItem(int i, std::vector<int>* l, bool should_throw = false)
: id(i), log(l)
{
if (should_throw) {
throw std::runtime_error{"ctor throw"};
}
}
~TrackedItem()
{
if (log != nullptr) {
log->push_back(id);
}
}
};
} // namespace
Void::Testing::Test arena_fixed_buffer_overalign_and_zero_bytes()
{
// Deliberately shift base pointer by 1 byte inside buffer to test true
// address alignment.
std::array<std::byte, 512> raw{};
Void::Memory::Arena arena{std::span<std::byte>{raw}.subspan(1)};
auto z = arena.try_allocate(0, 1);
Void::Testing::expect(z.has_value());
Void::Testing::expect_eq(arena.stats().requested_live, std::size_t{1});
auto a64 = arena.try_allocate(16, 64);
Void::Testing::expect(a64.has_value());
Void::Testing::expect_eq(
reinterpret_cast<std::uintptr_t>(*a64) % 64, std::uintptr_t{0});
const auto bad_align = arena.try_allocate(8, 3);
Void::Testing::expect(!bad_align.has_value());
Void::Testing::expect(bad_align.error() ==
Void::Memory::AllocationError::invalid_alignment);
const auto too_big = arena.try_allocate(1024, 8);
Void::Testing::expect(!too_big.has_value());
Void::Testing::expect(too_big.error() ==
Void::Memory::AllocationError::exhausted);
}
Void::Testing::Test arena_grows_slabs_and_rewinds_checkpoints()
{
Void::Memory::Arena arena{1024, 128};
auto p1 = arena.try_allocate(96, 8);
Void::Testing::expect(p1.has_value());
const auto cp1 = arena.checkpoint();
auto p2 = arena.try_allocate(128, 16);
Void::Testing::expect(p2.has_value());
const auto cp2 = arena.checkpoint();
Void::Testing::expect(arena.stats().committed_live >= 256);
Void::Testing::expect(arena.rewind(cp1).has_value());
Void::Testing::expect_eq(arena.stats().requested_live, std::size_t{96});
// Forward/beyond-cursor checkpoint must be rejected after rewind.
const auto bad_cp2 = arena.rewind(cp2);
Void::Testing::expect(!bad_cp2.has_value());
Void::Testing::expect(bad_cp2.error() ==
Void::Memory::AllocationError::invalid_checkpoint);
// Reusing space after rewind should not blow past budget unnecessarily.
auto p3 = arena.try_allocate(128, 16);
Void::Testing::expect(p3.has_value());
Void::Testing::expect(arena.reset().has_value());
Void::Testing::expect_eq(arena.stats().requested_live, std::size_t{0});
// Stale generation checkpoint rejected after reset().
const auto stale = arena.rewind(cp1);
Void::Testing::expect(!stale.has_value());
Void::Testing::expect(stale.error() ==
Void::Memory::AllocationError::invalid_checkpoint);
}
Void::Testing::Test arena_typed_scope_destroys_reverse_and_blocks_reset()
{
Void::Memory::Arena arena{4096, 512};
std::vector<int> destroyed;
{
Void::Memory::Arena::TypedScope scope{arena};
Void::Testing::expect(scope.emplace<TrackedItem>(1, &destroyed).has_value());
Void::Testing::expect(scope.emplace<TrackedItem>(2, &destroyed).has_value());
bool threw = false;
try {
(void)scope.emplace<TrackedItem>(99, &destroyed, true);
} catch (const std::runtime_error&) {
threw = true;
}
Void::Testing::expect(threw);
const auto blocked = arena.reset();
Void::Testing::expect(!blocked.has_value());
Void::Testing::expect(blocked.error() ==
Void::Memory::AllocationError::live_allocations);
}
Void::Testing::expect_eq(destroyed.size(), std::size_t{2});
Void::Testing::expect_eq(destroyed[0], 2);
Void::Testing::expect_eq(destroyed[1], 1);
Void::Testing::expect(arena.reset().has_value());
}
+104
View File
@@ -0,0 +1,104 @@
#include <Void/Memory/BlockPool.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstddef>
#include <memory_resource>
#include <thread>
#include <vector>
namespace
{
class CountingUpstream final : public std::pmr::memory_resource
{
public:
std::size_t slab_allocs{0};
std::size_t slab_frees{0};
private:
void* do_allocate(std::size_t bytes, std::size_t alignment) override
{
++slab_allocs;
return std::pmr::get_default_resource()->allocate(bytes, alignment);
}
void do_deallocate(void* p, std::size_t bytes,
std::size_t alignment) override
{
++slab_frees;
std::pmr::get_default_resource()->deallocate(p, bytes, alignment);
}
bool do_is_equal(
const std::pmr::memory_resource& other) const noexcept override
{
return this == &other;
}
};
} // namespace
Void::Testing::Test block_pool_recycles_without_upstream_allocs_and_trims_idle()
{
CountingUpstream upstream;
Void::Memory::BlockPool pool{32, 16, /*max_blocks=*/6,
/*max_committed=*/4096,
/*blocks_per_slab=*/2, upstream};
std::vector<void*> ptrs;
for (int i = 0; i < 6; ++i) {
auto r = pool.try_allocate();
Void::Testing::expect(r.has_value());
ptrs.push_back(*r);
}
Void::Testing::expect_eq(upstream.slab_allocs, std::size_t{3});
const auto full = pool.try_allocate();
Void::Testing::expect(!full.has_value());
Void::Testing::expect(full.error() ==
Void::Memory::AllocationError::exhausted);
// Return slab 1 completely (ptrs 2, 3) and leave slab 0 (ptr 0) and slab 2 (ptr 4) live.
pool.deallocate(ptrs[1]);
pool.deallocate(ptrs[2]);
pool.deallocate(ptrs[3]);
pool.deallocate(ptrs[5]);
// Recycle must hit existing free list without calling upstream!
const std::size_t allocs_before = upstream.slab_allocs;
auto recycled = pool.try_allocate();
Void::Testing::expect(recycled.has_value());
Void::Testing::expect_eq(upstream.slab_allocs, allocs_before);
pool.deallocate(*recycled);
// Re-free ptrs[1..3,5] state: ptrs[2] and ptrs[3] were slab 1 -> idle!
const std::size_t reclaimed = pool.trim_idle();
Void::Testing::expect(reclaimed > 0);
Void::Testing::expect_eq(upstream.slab_frees, std::size_t{1});
Void::Testing::expect_eq(pool.live_blocks(), std::size_t{2});
pool.deallocate(ptrs[0]);
pool.deallocate(ptrs[4]);
(void)pool.trim_idle();
Void::Testing::expect_eq(pool.live_blocks(), std::size_t{0});
Void::Testing::expect_eq(pool.capacity_blocks(), std::size_t{0});
}
Void::Testing::Test synchronized_block_pool_concurrent_alloc_dealloc()
{
Void::Memory::SynchronizedBlockPool pool{64, 8, 256, 65536, 16};
std::vector<std::thread> threads;
for (int t = 0; t < 4; ++t) {
threads.emplace_back([&]() {
for (int i = 0; i < 100; ++i) {
if (auto p = pool.try_allocate()) {
*static_cast<int*>(*p) = i;
pool.deallocate(*p);
}
}
});
}
for (auto& th : threads) {
th.join();
}
Void::Testing::expect_eq(pool.stats().requested_live, std::size_t{0});
}
+146
View File
@@ -0,0 +1,146 @@
#include <Void/Memory/BudgetResource.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <cstddef>
#include <limits>
#include <memory_resource>
#include <new>
#include <thread>
#include <vector>
namespace
{
class FailingUpstream final : public std::pmr::memory_resource
{
public:
bool fail_next{false};
std::size_t live_allocs{0};
private:
void* do_allocate(std::size_t bytes, std::size_t alignment) override
{
if (fail_next) {
throw std::bad_alloc{};
}
++live_allocs;
return std::pmr::get_default_resource()->allocate(bytes, alignment);
}
void do_deallocate(void* p, std::size_t bytes,
std::size_t alignment) override
{
--live_allocs;
std::pmr::get_default_resource()->deallocate(p, bytes, alignment);
}
bool do_is_equal(
const std::pmr::memory_resource& other) const noexcept override
{
return this == &other;
}
};
} // namespace
Void::Testing::Test budget_enforces_zero_exact_and_overflow_limits()
{
Void::Memory::BudgetResource zero_cap{0};
const auto r0 = zero_cap.try_allocate(1, 1);
Void::Testing::expect(!r0.has_value());
Void::Testing::expect(r0.error() ==
Void::Memory::AllocationError::exhausted);
Void::Memory::BudgetResource cap{128};
const auto bad_align = cap.try_allocate(16, 3);
Void::Testing::expect(!bad_align.has_value());
Void::Testing::expect(bad_align.error() ==
Void::Memory::AllocationError::invalid_alignment);
auto p1 = cap.try_allocate(64, 16);
Void::Testing::expect(p1.has_value());
auto p2 = cap.try_allocate(64, 16);
Void::Testing::expect(p2.has_value());
auto p3 = cap.try_allocate(1, 1);
Void::Testing::expect(!p3.has_value());
Void::Testing::expect(p3.error() ==
Void::Memory::AllocationError::exhausted);
Void::Memory::BudgetResource unlim{Void::Memory::unlimited};
auto ok_u = unlim.try_allocate(32, 8);
Void::Testing::expect(ok_u.has_value());
const auto ovf =
unlim.try_allocate(std::numeric_limits<std::size_t>::max(), 8);
Void::Testing::expect(!ovf.has_value());
Void::Testing::expect(ovf.error() ==
Void::Memory::AllocationError::size_overflow);
unlim.deallocate_checked(*ok_u, 32, 8);
cap.deallocate_checked(*p1, 64, 16);
cap.deallocate_checked(*p2, 64, 16);
const auto st = cap.stats();
Void::Testing::expect_eq(st.committed_live, std::size_t{0});
Void::Testing::expect_eq(st.peak_committed, std::size_t{128});
Void::Testing::expect_eq(st.allocations, std::uint64_t{2});
Void::Testing::expect_eq(st.deallocations, std::uint64_t{2});
Void::Testing::expect_eq(st.failures, std::uint64_t{2});
}
Void::Testing::Test budget_rolls_back_reservation_on_upstream_failure()
{
FailingUpstream upstream;
Void::Memory::BudgetResource budget{256, upstream};
auto ok = budget.try_allocate(64, 8);
Void::Testing::expect(ok.has_value());
upstream.fail_next = true;
const auto fail = budget.try_allocate(128, 8);
Void::Testing::expect(!fail.has_value());
Void::Testing::expect(fail.error() ==
Void::Memory::AllocationError::upstream_failure);
Void::Testing::expect_eq(budget.stats().committed_live, std::size_t{64});
// After upstream failure rollback, full remaining budget is still usable.
upstream.fail_next = false;
auto ok2 = budget.try_allocate(192, 8);
Void::Testing::expect(ok2.has_value());
budget.deallocate_checked(*ok, 64, 8);
budget.deallocate_checked(*ok2, 192, 8);
Void::Testing::expect_eq(upstream.live_allocs, std::size_t{0});
}
Void::Testing::Test budget_pmr_throws_bad_alloc_and_supports_threads()
{
Void::Memory::BudgetResource tiny{16};
bool threw = false;
try {
std::pmr::vector<std::byte> v{&tiny};
v.resize(64);
} catch (const std::bad_alloc&) {
threw = true;
}
Void::Testing::expect(threw);
Void::Testing::expect_eq(tiny.stats().committed_live, std::size_t{0});
Void::Memory::BudgetResource shared{4096};
std::atomic<int> successes{0};
std::vector<std::thread> workers;
for (int t = 0; t < 4; ++t) {
workers.emplace_back([&]() {
for (int i = 0; i < 100; ++i) {
if (auto p = shared.try_allocate(64, 8)) {
successes.fetch_add(1, std::memory_order_relaxed);
shared.deallocate_checked(*p, 64, 8);
}
}
});
}
for (auto& w : workers) {
w.join();
}
Void::Testing::expect(successes.load() > 0);
Void::Testing::expect_eq(shared.stats().committed_live, std::size_t{0});
}