Merge pull request 'Bounded sparse 3D pages with atomic revision-checked batches (#14)' (#30) from issue/14-sparse-page-table into main

This commit was merged in pull request #30.
This commit is contained in:
faumaray committed 2026-12-03 08:08:33 +00:00
commit b381d682c8
2 files changed
+516

No files matched your search

+323
View File
@@ -0,0 +1,323 @@
#pragma once
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <map>
#include <optional>
#include <set>
#include <span>
#include <utility>
#include <vector>
namespace Void::Containers
{
/// Finite sparse 3D page table with revision-checked atomic edit batches.
///
/// Cells are grouped into fixed `PageSize`-cubed pages. Pages are allocated on
/// demand (a missing page reads as `empty` with revision 0) and bounded by
/// `Limits::max_pages`. `apply` validates every precondition, budget and
/// revision before touching the table; on failure nothing changes.
///
/// Batch semantics:
/// - Duplicate cell addresses in one batch are rejected.
/// - An edit whose value equals the current cell does not allocate a page and
/// does not bump a revision.
/// - `expected_revision` is checked against the page revision at batch start
/// (0 for a missing page).
/// - A changed page whose revision is already the maximum fails the batch.
/// - The result lists changed pages sorted by page identity with their new
/// revisions.
///
/// Single-threaded by contract; callers synchronize concurrent access.
template <typename Cell, std::size_t PageSize = 32> class SparsePageTable
{
public:
static_assert(PageSize > 0);
static constexpr std::size_t kPageSize = PageSize;
static constexpr std::size_t kCellsPerPage =
PageSize * PageSize * PageSize;
using Revision = std::uint64_t;
struct PageId {
std::int64_t x{0};
std::int64_t y{0};
std::int64_t z{0};
[[nodiscard]] auto
operator<=>(const PageId&) const noexcept = default;
[[nodiscard]] bool
operator==(const PageId&) const noexcept = default;
};
struct CellAddress {
std::int64_t x{0};
std::int64_t y{0};
std::int64_t z{0};
[[nodiscard]] auto
operator<=>(const CellAddress&) const noexcept = default;
[[nodiscard]] bool
operator==(const CellAddress&) const noexcept = default;
};
struct Edit {
CellAddress address;
Cell value;
std::optional<Revision> expected_revision{};
[[nodiscard]] bool
operator==(const Edit&) const = default;
};
struct Limits {
std::size_t max_pages{1024};
};
enum class EditStatus : std::uint8_t {
committed = 0,
/// A page's expected revision did not match the current one.
stale_revision,
/// A changed page already has the maximum revision.
revision_exhausted,
/// The batch would allocate more pages than the budget allows.
page_budget_exceeded,
/// The same cell address appears twice in the batch.
duplicate_edit,
};
struct ChangedPage {
PageId page;
Revision revision{0};
[[nodiscard]] bool
operator==(const ChangedPage&) const = default;
};
struct EditResult {
EditStatus status{EditStatus::committed};
std::vector<ChangedPage> changed{};
[[nodiscard]] bool committed() const noexcept
{
return status == EditStatus::committed;
}
};
struct PageState {
PageId page;
Revision revision{0};
std::array<Cell, kCellsPerPage> cells{};
[[nodiscard]] bool operator==(const PageState&) const = default;
};
struct State {
std::vector<PageState> pages;
[[nodiscard]] bool operator==(const State&) const = default;
};
explicit SparsePageTable(Limits limits = Limits{},
Cell empty = Cell{})
: limits_(limits)
, empty_(std::move(empty))
{
}
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
[[nodiscard]] const Cell& empty_value() const noexcept
{
return empty_;
}
[[nodiscard]] std::size_t page_count() const noexcept
{
return pages_.size();
}
/// Cell value; a missing page yields `empty_value()`.
[[nodiscard]] Cell get(CellAddress address) const
{
const auto [id, offset] = locate(address);
const auto found = pages_.find(id);
if (found == pages_.end()) {
return empty_;
}
return found->second.cells[offset];
}
/// Page revision, or `nullopt` when the page is not allocated.
[[nodiscard]] std::optional<Revision>
page_revision(PageId page) const
{
const auto found = pages_.find(page);
if (found == pages_.end()) {
return std::nullopt;
}
return found->second.revision;
}
/// Apply all edits or none.
[[nodiscard]] EditResult apply(std::span<const Edit> edits)
{
if (edits.empty()) {
return EditResult{};
}
std::set<CellAddress> seen;
std::map<PageId, std::vector<const Edit*>> grouped;
for (const auto& edit : edits) {
if (!seen.insert(edit.address).second) {
return EditResult{.status =
EditStatus::duplicate_edit};
}
grouped[page_of(edit.address)].push_back(&edit);
}
std::map<PageId, bool> changes;
std::size_t new_pages = 0;
for (const auto& [id, page_edits] : grouped) {
const auto found = pages_.find(id);
const Page* page =
found == pages_.end() ? nullptr : &found->second;
const Revision revision = page == nullptr ? 0
: page->revision;
for (const Edit* edit : page_edits) {
if (edit->expected_revision.has_value() &&
*edit->expected_revision != revision) {
return EditResult{
.status = EditStatus::stale_revision};
}
}
bool changed = false;
for (const Edit* edit : page_edits) {
const auto offset = offset_of(edit->address);
const Cell& current =
page == nullptr ? empty_ : page->cells[offset];
if (!(current == edit->value)) {
changed = true;
break;
}
}
if (!changed) {
continue;
}
if (revision ==
std::numeric_limits<Revision>::max()) {
return EditResult{
.status = EditStatus::revision_exhausted};
}
changes.emplace(id, true);
if (page == nullptr) {
++new_pages;
}
}
if (pages_.size() + new_pages > limits_.max_pages) {
return EditResult{.status =
EditStatus::page_budget_exceeded};
}
EditResult result;
for (const auto& [id, changed] : changes) {
(void)changed;
auto& page = pages_[id];
for (const Edit* edit : grouped.at(id)) {
page.cells[offset_of(edit->address)] = edit->value;
}
++page.revision;
result.changed.push_back(
ChangedPage{.page = id, .revision = page.revision});
}
return result;
}
[[nodiscard]] State save() const
{
State state;
state.pages.reserve(pages_.size());
for (const auto& [id, page] : pages_) {
state.pages.push_back(PageState{
.page = id, .revision = page.revision, .cells = page.cells});
}
return state;
}
/// Restore saved pages. Rejects duplicate page ids, more pages than the
/// limit, or a page with no revision left for an edit.
[[nodiscard]] static std::optional<SparsePageTable>
restore(State state, Limits limits = Limits{},
Cell empty = Cell{})
{
if (state.pages.size() > limits.max_pages) {
return std::nullopt;
}
SparsePageTable table{limits, std::move(empty)};
for (auto& saved : state.pages) {
if (!table.pages_
.emplace(saved.page,
Page{.cells = saved.cells,
.revision = saved.revision})
.second) {
return std::nullopt;
}
}
return table;
}
private:
struct Page {
std::array<Cell, kCellsPerPage> cells{};
Revision revision{0};
};
[[nodiscard]] static std::pair<std::int64_t, std::size_t>
split(std::int64_t coordinate)
{
constexpr auto size = static_cast<std::int64_t>(PageSize);
std::int64_t page = coordinate / size;
std::int64_t offset = coordinate % size;
if (offset < 0) {
--page;
offset += size;
}
return {page, static_cast<std::size_t>(offset)};
}
[[nodiscard]] static PageId page_of(CellAddress address)
{
return PageId{.x = split(address.x).first,
.y = split(address.y).first,
.z = split(address.z).first};
}
[[nodiscard]] static std::size_t offset_of(CellAddress address)
{
const auto [px, ox] = split(address.x);
const auto [py, oy] = split(address.y);
const auto [pz, oz] = split(address.z);
(void)px;
(void)py;
(void)pz;
return (oz * PageSize + oy) * PageSize + ox;
}
[[nodiscard]] static std::pair<PageId, std::size_t>
locate(CellAddress address)
{
return {page_of(address), offset_of(address)};
}
Limits limits_{};
Cell empty_{};
std::map<PageId, Page> pages_;
};
} // namespace Void::Containers