#ifndef TINYFSM_HPP #define TINYFSM_HPP #include #include namespace tinyfsm { struct Event {}; template class Fsm { public: using state_factory_t = std::unique_ptr(*)(); static void start() { if (!current_state_) { auto factory = initial_state_factory(); current_state_ = factory ? factory() : std::make_unique(); current_state_->entry(); apply_pending_transition(); } } template static void dispatch(const EventT& event) { start(); pending_state_factory() = nullptr; current_state_->react(event); apply_pending_transition(); } template static void set_initial_state() { initial_state_factory() = []() -> std::unique_ptr { return std::make_unique(); }; } protected: template void transit() { pending_state_factory() = []() -> std::unique_ptr { return std::make_unique(); }; } private: static state_factory_t& initial_state_factory() { static state_factory_t factory = nullptr; return factory; } static state_factory_t& pending_state_factory() { static state_factory_t factory = nullptr; return factory; } static void apply_pending_transition() { while (auto factory = pending_state_factory()) { pending_state_factory() = nullptr; if (current_state_) { current_state_->exit(); } current_state_ = factory(); current_state_->entry(); } } inline static std::unique_ptr current_state_{}; }; } // namespace tinyfsm #define FSM_INITIAL_STATE(FSM, STATE) \ namespace { \ const bool FSM##_initial_state_registered = []() { \ FSM::template set_initial_state(); \ return true; \ }(); \ } #endif // TINYFSM_HPP