feat(Memory): add Memory subsystem with BudgetResource, Arena, and BlockPool (S-MEMORY-02..04)
This commit is contained in:
1 parent
4227348051
commit
4d48f2a8f2
11 files changed
+1306
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user