Skip to content

Instantly share code, notes, and snippets.

@palacaze
Created February 25, 2021 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save palacaze/07f511f13bd5e666fb66b5767c52ecd5 to your computer and use it in GitHub Desktop.
Save palacaze/07f511f13bd5e666fb66b5767c52ecd5 to your computer and use it in GitHub Desktop.
Variant based state machine
// state machine that handes processing of data
struct Fetch {};
struct Stop {};
struct StartProcessing {
SamplePtr sample;
};
struct WaitProcessed {
SamplePtr sample;
std::string json_path;
};
struct FinishProcessing {
SamplePtr sample;
std::string json_path;
bool ok;
};
struct Reconstruct {
SamplePtr sample;
};
struct Send {
SamplePtr sample;
};
using State = std::variant<Fetch, StartProcessing, WaitProcessed, FinishProcessing, Reconstruct, Send, Stop>;
State handle(Fetch &s);
State handle(StartProcessing &s);
State handle(WaitProcessed &s);
State handle(FinishProcessing &s);
State handle(Reconstruct &s) {
reconstruct(s.sample);
return Send{s.sample};
}
State handle(Send &s) {
send(std::move(s));
return Fetch{};
}
State handle(Stop &s) {
return s;
}
void run() {
State state = Fetch{};
while (!std::holds_alternative<Stop>(state)) {
state = std::visit([=](auto &a) { return handle(a); }, state);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment