strawberry/include/tinyfsm.hpp

83 lines
2.3 KiB
C++

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