Merge branch 'issue/7-restorable-id-sequences'

This commit is contained in:
selikhov committed 2026-12-03 09:41:52 +03:00
commit 7232fa4ba5
2 files changed
+331

No files matched your search

+183
View File
@@ -0,0 +1,183 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <limits>
#include <optional>
namespace Void::Core
{
enum class SequenceErrorKind : std::uint8_t {
/// The requested id or batch does not fit in the remaining range.
exhausted = 0,
/// A batch of zero ids was requested.
zero_count,
/// The supplied saved state is not a valid sequence state.
invalid_state,
};
struct SequenceError {
SequenceErrorKind kind{SequenceErrorKind::exhausted};
/// How many ids were still available when the request failed.
std::uint64_t available{0};
};
/// Instance-owned, restorable id sequence with checked exhaustion.
///
/// Unlike `Void::Counted::SeqId<Tag>` (one process-wide atomic per tag), each
/// `IdSequence` owns its own state. It can be copied at a completed boundary,
/// saved and restored, and several instances (e.g. two worlds in one process)
/// allocate independently.
///
/// Ids start at 1. A removed record never gives its id back: the high-water
/// mark only moves forward, including across save/restore. `next()` and
/// `next_batch()` return `exhausted` *before* changing state when the request
/// does not fit, so a failed allocation leaves both the sequence and any
/// application record untouched.
///
/// `Rep` is the fixed-width representation used in saved state (default
/// `std::uint64_t`), making cross-platform saves reproducible. `Tag` keeps
/// unrelated id domains from being confused at compile time.
///
/// The class is not thread-safe; callers synchronize concurrent access to one
/// instance.
template <typename Tag = void, typename Rep = std::uint64_t> class IdSequence
{
public:
using value_type = Rep;
/// Serializable position. `exhausted` distinguishes "max is still
/// available" (`next == max`) from "max was already handed out".
struct State {
value_type next{1};
bool exhausted{false};
[[nodiscard]] auto
operator<=>(const State&) const noexcept = default;
[[nodiscard]] bool
operator==(const State&) const noexcept = default;
};
struct Batch {
value_type first{0};
value_type count{0};
};
constexpr IdSequence() noexcept = default;
explicit constexpr IdSequence(value_type first) noexcept
: state_{.next = first == 0 ? value_type{1} : first}
{
}
/// Allocate one id.
[[nodiscard]] std::expected<value_type, SequenceError> next()
{
if (state_.exhausted) {
return fail(SequenceErrorKind::exhausted);
}
const value_type id = state_.next;
if (id == maximum()) {
state_.exhausted = true;
} else {
state_.next = static_cast<value_type>(id + 1);
}
return id;
}
/// Reserve a contiguous batch atomically: either all `count` ids are
/// reserved or none are.
[[nodiscard]] std::expected<Batch, SequenceError>
next_batch(std::size_t count)
{
if (count == 0) {
return fail(SequenceErrorKind::zero_count);
}
if (state_.exhausted) {
return fail(SequenceErrorKind::exhausted);
}
const auto remaining = static_cast<std::uintmax_t>(available());
if (static_cast<std::uintmax_t>(count) > remaining) {
return fail(SequenceErrorKind::exhausted);
}
const value_type first = state_.next;
const auto step = static_cast<value_type>(count);
if (static_cast<std::uintmax_t>(step) == remaining) {
state_.exhausted = true;
} else {
state_.next = static_cast<value_type>(first + step);
}
return Batch{.first = first, .count = step};
}
/// How many ids can still be allocated.
[[nodiscard]] value_type available() const noexcept
{
if (state_.exhausted) {
return 0;
}
return static_cast<value_type>(maximum() - state_.next + 1);
}
[[nodiscard]] bool exhausted() const noexcept
{
return state_.exhausted;
}
/// The next id that would be handed out (or max once exhausted).
[[nodiscard]] value_type peek() const noexcept { return state_.next; }
/// Highest id ever handed out (0 before the first allocation).
[[nodiscard]] value_type high_water() const noexcept
{
if (state_.exhausted) {
return maximum();
}
return state_.next == 1 ? value_type{0}
: static_cast<value_type>(state_.next - 1);
}
[[nodiscard]] State state() const noexcept { return state_; }
/// Restore a saved state. Rejects non-canonical or impossible states;
/// on success the sequence continues exactly after the saved position.
[[nodiscard]] static std::expected<IdSequence, SequenceError>
restore(State state)
{
if (state.next == 0) {
return std::unexpected{SequenceError{
.kind = SequenceErrorKind::invalid_state, .available = 0}};
}
if (state.exhausted && state.next != maximum()) {
return std::unexpected{SequenceError{
.kind = SequenceErrorKind::invalid_state,
.available = 0}};
}
IdSequence sequence;
sequence.state_ = state;
return sequence;
}
[[nodiscard]] static constexpr value_type maximum() noexcept
{
return std::numeric_limits<value_type>::max();
}
private:
[[nodiscard]] std::unexpected<SequenceError>
fail(SequenceErrorKind kind) const
{
return std::unexpected{SequenceError{
.kind = kind,
.available = static_cast<std::uint64_t>(available())}};
}
State state_{};
};
} // namespace Void::Core
+148
View File
@@ -0,0 +1,148 @@
#include <Void/Core/Sequence.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstdint>
#include <type_traits>
namespace
{
struct WorldTag {};
struct OtherWorldTag {};
using WorldSequence = Void::Core::IdSequence<WorldTag>;
using SmallSequence = Void::Core::IdSequence<WorldTag, std::uint8_t>;
} // namespace
Void::Testing::Test id_sequence_allocates_monotonically()
{
WorldSequence sequence;
Void::Testing::expect_eq(*sequence.next(), std::uint64_t{1});
Void::Testing::expect_eq(*sequence.next(), std::uint64_t{2});
Void::Testing::expect_eq(*sequence.next(), std::uint64_t{3});
Void::Testing::expect_eq(sequence.high_water(), std::uint64_t{3});
Void::Testing::expect_eq(sequence.peek(), std::uint64_t{4});
}
Void::Testing::Test id_sequence_instances_are_independent()
{
WorldSequence first;
WorldSequence second;
Void::Testing::expect_eq(*first.next(), std::uint64_t{1});
Void::Testing::expect_eq(*second.next(), std::uint64_t{1});
Void::Testing::expect_eq(*first.next(), std::uint64_t{2});
Void::Testing::expect_eq(*second.next(), std::uint64_t{2});
}
Void::Testing::Test id_sequence_restore_retires_erased_high_water()
{
WorldSequence sequence;
(void)sequence.next();
(void)sequence.next();
const auto erased = *sequence.next(); // record 3 is erased by the caller
Void::Testing::expect_eq(erased, std::uint64_t{3});
const auto saved = sequence.state();
auto restored = WorldSequence::restore(saved);
Void::Testing::require(restored.has_value());
// The erased id is retired, not reused.
Void::Testing::expect_eq(*restored->next(), std::uint64_t{4});
}
Void::Testing::Test id_sequence_copy_replays_from_snapshot()
{
WorldSequence original;
(void)original.next();
(void)original.next();
auto snapshot = original; // copy at a completed boundary
Void::Testing::expect_eq(*snapshot.next(), std::uint64_t{3});
Void::Testing::expect_eq(*original.next(), std::uint64_t{3});
}
Void::Testing::Test id_sequence_batch_is_atomic()
{
WorldSequence sequence;
auto batch = sequence.next_batch(3);
Void::Testing::require(batch.has_value());
Void::Testing::expect_eq(batch->first, std::uint64_t{1});
Void::Testing::expect_eq(batch->count, std::uint64_t{3});
Void::Testing::expect_eq(*sequence.next(), std::uint64_t{4});
// A batch that does not fit changes nothing.
SmallSequence small{250};
const auto before = small.state();
auto too_large = small.next_batch(10);
Void::Testing::expect(!too_large.has_value());
Void::Testing::expect(small.state() == before);
}
Void::Testing::Test id_sequence_zero_batch_is_rejected()
{
WorldSequence sequence;
auto zero = sequence.next_batch(0);
Void::Testing::require(!zero.has_value());
Void::Testing::expect(zero.error().kind ==
Void::Core::SequenceErrorKind::zero_count);
Void::Testing::expect_eq(sequence.peek(), std::uint64_t{1});
}
Void::Testing::Test id_sequence_checked_exhaustion()
{
SmallSequence sequence{254};
Void::Testing::expect_eq(static_cast<int>(*sequence.next()), 254);
Void::Testing::expect_eq(static_cast<int>(*sequence.next()), 255);
Void::Testing::expect(sequence.exhausted());
Void::Testing::expect_eq(static_cast<int>(sequence.available()), 0);
const auto before = sequence.state();
auto overflow = sequence.next();
Void::Testing::require(!overflow.has_value());
Void::Testing::expect(overflow.error().kind ==
Void::Core::SequenceErrorKind::exhausted);
Void::Testing::expect(sequence.state() == before);
Void::Testing::expect_eq(static_cast<int>(sequence.high_water()), 255);
}
Void::Testing::Test id_sequence_batch_at_final_boundary()
{
SmallSequence sequence{255};
// Only max is available: a batch of two is rejected without change.
const auto before = sequence.state();
auto two = sequence.next_batch(2);
Void::Testing::require(!two.has_value());
Void::Testing::expect(two.error().kind ==
Void::Core::SequenceErrorKind::exhausted);
Void::Testing::expect(sequence.state() == before);
// A batch of exactly the remaining one succeeds and exhausts.
auto one = sequence.next_batch(1);
Void::Testing::require(one.has_value());
Void::Testing::expect_eq(static_cast<int>(one->first), 255);
Void::Testing::expect(sequence.exhausted());
}
Void::Testing::Test id_sequence_restore_rejects_invalid_state()
{
using State = SmallSequence::State;
auto zero = SmallSequence::restore(State{.next = 0, .exhausted = false});
Void::Testing::expect(!zero.has_value());
Void::Testing::expect(zero.error().kind ==
Void::Core::SequenceErrorKind::invalid_state);
auto inconsistent =
SmallSequence::restore(State{.next = 10, .exhausted = true});
Void::Testing::expect(!inconsistent.has_value());
}
Void::Testing::Test id_sequence_state_is_fixed_width()
{
using Sequence = Void::Core::IdSequence<WorldTag, std::uint32_t>;
static_assert(
std::is_same_v<decltype(Sequence::State{}.next), std::uint32_t>);
Sequence sequence;
(void)sequence.next();
const auto state = sequence.state();
Void::Testing::expect_eq(state.next, std::uint32_t{2});
}