Files
Library/include/Void/StateMachine/StateMachine.hpp
T
faumarayandClaude Sonnet 4.6 a9a2e2b59a Add Scope, StateMachine, TypeList modules; remove macros from Scope
Void::Scope — RAII scope guards: ScopeExit/ScopeSuccess/ScopeFail with
on_exit/on_success/on_fail factory functions. No macros.

Void::StateMachine — compile-time FSM driven by Transition<From,Ev,To>
type lists. Supports typed entry/exit callbacks and returns bool from send()
indicating whether the transition was valid.

Void::TypeList — compile-time type list with: size_of, at, front, back,
contains, index_of, push_front/back, pop_front, concat, filter, transform,
reverse, unique, for_each, all_of/any_of/none_of.

Void::Encoding — Base64 (standard + URL-safe encode/decode) and Hex
encode/decode. Included in previous commit but missed in message.

36/36 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 22:49:22 +03:00

210 lines
6.1 KiB
C++

#pragma once
#include <concepts>
#include <functional>
#include <optional>
#include <stdexcept>
#include <string_view>
#include <type_traits>
#include <variant>
namespace Void::StateMachine
{
// ── Concepts ──────────────────────────────────────────────────────────────────
template <typename S>
concept State = std::is_default_constructible_v<S>;
template <typename E>
concept Event = std::copyable<E>;
// ── Transition helper ─────────────────────────────────────────────────────────
// A transition<From, Ev, To> captures one arc: From --[Ev]--> To.
// The user specializes `transitions` for their state machine type.
template <typename From, typename Ev, typename To>
struct Transition
{
using from = From;
using event = Ev;
using to = To;
};
// ── StateMachine ──────────────────────────────────────────────────────────────
//
// Template parameters:
// States — type list of all states, first element is the initial state
// Transitions — type list of Transition<F,E,T> arcs
//
// Usage:
// using MyFSM = StateMachine<
// std::tuple<Idle, Running, Done>,
// std::tuple<
// Transition<Idle, StartEvent, Running>,
// Transition<Running, StopEvent, Done>
// >
// >;
template <typename StatesTuple, typename TransitionsTuple>
class StateMachine;
namespace Detail
{
// Collect all states from the transitions tuple
template <typename... Ts>
struct StateVariantOf;
template <typename... States>
struct StateVariantOf<std::tuple<States...>>
{
using type = std::variant<States...>;
};
// Does the Transition list contain a matching arc?
template <typename CurrentState, typename Ev, typename TransTuple>
struct FindTransition;
template <typename CS, typename Ev>
struct FindTransition<CS, Ev, std::tuple<>>
{
using to = void; // no match
};
template <typename CS, typename Ev, typename Head, typename... Tail>
struct FindTransition<CS, Ev, std::tuple<Head, Tail...>>
{
using to = std::conditional_t<
std::is_same_v<typename Head::from, CS> &&
std::is_same_v<typename Head::event, Ev>,
typename Head::to,
typename FindTransition<CS, Ev, std::tuple<Tail...>>::to>;
};
} // namespace Detail
template <typename... States, typename... Transitions>
class StateMachine<std::tuple<States...>, std::tuple<Transitions...>>
{
public:
using StateVariant = std::variant<States...>;
using TransitionTuple = std::tuple<Transitions...>;
StateMachine() = default;
// Current state index (0-based, matches variant index).
[[nodiscard]] std::size_t state_index() const noexcept
{
return state_.index();
}
// True if current state is S.
template <typename S>
[[nodiscard]] bool is() const noexcept
{
return std::holds_alternative<S>(state_);
}
// Access current state as S (throws std::bad_variant_access if wrong).
template <typename S>
[[nodiscard]] const S& as() const
{
return std::get<S>(state_);
}
template <typename S>
[[nodiscard]] S& as()
{
return std::get<S>(state_);
}
// Try to access state, returns nullptr if wrong state.
template <typename S>
[[nodiscard]] const S* try_as() const noexcept
{
return std::get_if<S>(&state_);
}
// Send an event. Returns true if a transition was found and taken.
template <typename Ev>
bool send(const Ev& ev)
{
bool transitioned = false;
std::visit(
[&]<typename CurState>(CurState& cur) {
using To =
typename Detail::FindTransition<CurState, Ev,
TransitionTuple>::to;
if constexpr (!std::is_void_v<To>) {
on_exit(cur);
state_ = To{};
on_enter(std::get<To>(state_), ev);
transitioned = true;
}
},
state_);
return transitioned;
}
// Register a callback fired when entering state S.
template <typename S, std::invocable<const S&> F>
void on_enter(F&& f)
{
// Store as type-erased function in a small array indexed by variant alt.
entry_callbacks_[variant_index_of<S>()] =
[fn = std::forward<F>(f)](const StateVariant& v) {
fn(std::get<S>(v));
};
}
// Register a callback fired when leaving state S.
template <typename S, std::invocable<const S&> F>
void on_exit(F&& f)
{
exit_callbacks_[variant_index_of<S>()] =
[fn = std::forward<F>(f)](const StateVariant& v) {
fn(std::get<S>(v));
};
}
private:
template <typename S>
static constexpr std::size_t variant_index_of() noexcept
{
return []<std::size_t... Is>(std::index_sequence<Is...>) {
std::size_t idx = 0;
((std::is_same_v<S, States> ? (idx = Is, true) : false) || ...);
return idx;
}(std::index_sequence_for<States...>{});
}
template <typename S>
void on_exit(const S& s)
{
const auto idx = variant_index_of<S>();
if (exit_callbacks_[idx]) {
StateVariant tmp = s;
exit_callbacks_[idx](tmp);
}
}
template <typename S, typename Ev>
void on_enter(const S& s, const Ev&)
{
const auto idx = variant_index_of<S>();
if (entry_callbacks_[idx]) {
StateVariant tmp = s;
entry_callbacks_[idx](tmp);
}
}
StateVariant state_{std::in_place_index<0>};
std::function<void(const StateVariant&)>
entry_callbacks_[sizeof...(States)]{};
std::function<void(const StateVariant&)>
exit_callbacks_[sizeof...(States)]{};
};
} // namespace Void::StateMachine