ZIO
Python and C++ interface to ZeroMQ and Zyre
test_sml.cpp
Go to the documentation of this file.
1 // example from readme
2 #include <iostream>
3 #include <cassert>
4 #include "sml.hpp"
5 namespace sml = boost::sml;
6 
7 // Dependencies
8 struct sender {
9  template<class TMsg>
10  constexpr void send(const TMsg& msg) { std::cout << "send: "<< msg.id << std::endl; }
11 };
12 
13 // Events
14 
15 struct ack { bool valid{}; };
16 struct fin { int id{}; bool valid{}; };
17 struct release {};
18 struct timeout {};
19 
20 // Guards
21 
22 constexpr auto is_valid = [](const auto& event) { return event.valid; };
23 
24 // Actions
25 
26 constexpr auto send_fin = [](sender& s) { s.send(fin{0}); };
27 constexpr auto send_ack = [](const auto& event, sender& s) { s.send(event); };
28 
29 // State Machine
30 
31 struct tcp_release /*final*/ {
32  auto operator()() const {
33  using namespace sml;
38  return make_transition_table(
39  *"established"_s + event<release> / send_fin = "fin wait 1"_s,
40  "fin wait 1"_s + event<ack> [ is_valid ] = "fin wait 2"_s,
41  "fin wait 2"_s + event<fin> [ is_valid ] / send_ack = "timed wait"_s,
42  "timed wait"_s + event<timeout> = X
43  );
44  }
45 };
46 
47 // Usage
48 
49 int main() {
50  using namespace sml;
51 
52  sender s{};
53  sm<tcp_release> mysm{s}; // pass dependencies via ctor
54  assert(mysm.is("established"_s));
55 
56  mysm.process_event(release{}); // complexity O(1)
57  assert(mysm.is("fin wait 1"_s));
58 
59  mysm.process_event(ack{true}); // prints 'send: 0'
60  assert(mysm.is("fin wait 2"_s));
61 
62  mysm.process_event(fin{42, true}); // prints 'send: 42'
63  assert(mysm.is("timed wait"_s));
64 
65  mysm.process_event(timeout{});
66  assert(mysm.is(X)); // terminated
67 }
Definition: test_sml.cpp:16
int main()
Definition: test_sml.cpp:49
Definition: test_sml.cpp:15
auto operator()() const
Definition: test_sml.cpp:32
constexpr void send(const TMsg &msg)
Definition: test_sml.cpp:10
constexpr auto send_fin
Definition: test_sml.cpp:26
constexpr auto is_valid
Definition: test_sml.cpp:22
constexpr auto send_ack
Definition: test_sml.cpp:27