Created
February 25, 2021 10:04
-
-
Save palacaze/07f511f13bd5e666fb66b5767c52ecd5 to your computer and use it in GitHub Desktop.
Variant based state machine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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