HFSM2
Search…
Serialization *

Quick Facts

Interface

hfsm2::Root::SerialBuffer
Buffer for serialization
hfsm2::Root::save(SerialBuffer&) const
Serialize the structural configuration
hfsm2::Root::load(const SerialBuffer&)
De-serialize the configuration and initialize FSM

Example

1
// Enable serialization
2
#define HFSM_ENABLE_SERIALIZATION
3
4
#include <hfsm2/machine.hpp>
5
#include <assert.h>
6
7
using M = hfsm2::Machine;
8
9
using FSM = M::PeerRoot<
10
struct State1,
11
struct State2
12
>;
13
14
struct State1 : FSM::State { /* .. */ };
15
struct State2 : FSM::State { /* .. */ };
16
17
int main() {
18
// Buffer for serialization
19
// Members:
20
// bitSize - Number of payload bits used
21
// payload - Serialized data
22
FSM::Instance::SerialBuffer buffer;
23
24
{
25
FSM::Instance fsm; // Create a new FSM instance
26
fsm.changeTo<State2>(); // Request a transition to 'State2'
27
fsm.update(); // Process transitions
28
assert(fsm.isActive<State2>()); // Check if transition completed
29
30
fsm.save(buffer); // Serialize FSM configuration into 'buffer'
31
}
32
33
{
34
FSM::Instance fsm; // Create a fresh FSM instance
35
assert(fsm.isActive<State1>()); // Initial 'State1' is activated by default
36
37
fsm.load(buffer); // De-serialize FSM from 'buffer'
38
assert(fsm.isActive<State2>()); // Check its configuration is restored
39
}
40
}
Copied!

Serialization Between Different FSMs

As demonstrated in test_serialization.cpp, it is allowed to exchange the SerialBuffer between different FSMs, so long as their hierarchical structure is exactly the same.
This can be useful for network replication between structurally equivalent server and client FSM instances implementing some specific logic.

SerialBuffer Size and Compression

HFSM2 does not compress SerialBuffer.
However, the configuration data saved to SerialBuffer::payload is tightly packed to use the minimal number of bits.
The number of bits used in the payload is recorded in SerialBuffer::bitSize, which could be used for example in custom network replication logic to minimize network bandwidth usage.
Compressing SerialBuffer can also be used to further reduce the size serialized state.
Last modified 1yr ago