#include #include #include #include #include #include #include using Void::Coro::Task; using Void::Fsm::MachineOptions; using Void::Fsm::Step; namespace { struct Input { int value; }; struct Stop { }; // Waits for Input events, accumulating until a Stop event arrives. class Accumulator : public Void::Fsm::Machine { public: int total = 0; std::vector* order = nullptr; struct Waiting : State { Task run() override { auto& m = self(); // Two typed mailboxes: pull whichever arrives. auto in = co_await await_event(); m.total += in.value; if (m.order) { m.order->push_back(in.value); } if (in.value == 0) { co_return succeed(m.total); } co_return next(); } }; explicit Accumulator(bool own_worker) : Void::Fsm::Machine( MachineOptions{.own_worker = own_worker}) { initial(); } }; } // namespace Void::Testing::Test fsm_await_event_buffered_then_consumed() { // Post before pumping — events buffer in the typed mailbox. Accumulator fsm{false}; fsm.start(); fsm.post(Input{5}); fsm.post(Input{7}); fsm.post(Input{0}); // terminator const auto outcome = fsm.run_blocking(); Void::Testing::expect(outcome.has_value()); Void::Testing::expect_eq(*outcome, 12); } Void::Testing::Test fsm_await_event_preserves_order() { std::vector order; Accumulator fsm{false}; fsm.order = ℴ fsm.start(); fsm.post(Input{1}); fsm.post(Input{2}); fsm.post(Input{3}); fsm.post(Input{0}); (void)fsm.run_blocking(); const std::vector expected{1, 2, 3, 0}; Void::Testing::expect(order == expected); } // @tag integration Void::Testing::Test fsm_await_event_cross_thread_with_worker() { Accumulator fsm{true}; // own worker thread fsm.start(); // Feed events from another thread while the worker awaits them. std::thread producer([&] { for (int i = 1; i <= 4; ++i) { fsm.post(Input{i}); std::this_thread::sleep_for(std::chrono::milliseconds{2}); } fsm.post(Input{0}); }); const auto outcome = fsm.wait(); // blocks until Stop terminator producer.join(); Void::Testing::expect(outcome.has_value()); Void::Testing::expect_eq(*outcome, 10); // 1+2+3+4 } Void::Testing::Test fsm_current_state_during_event_wait() { Accumulator fsm{false}; fsm.start(); fsm.pump(); // runs Waiting::run until it suspends on await_event Void::Testing::expect_eq(fsm.current_state(), std::string{"Waiting"}); Void::Testing::expect(!fsm.finished()); fsm.post(Input{0}); (void)fsm.wait(); Void::Testing::expect(fsm.finished()); }