This commit is contained in:
2022-11-05 15:40:30 -07:00
parent d96eafaa47
commit d6727ab770
2 changed files with 24 additions and 23 deletions

View File

@@ -2,6 +2,7 @@
#define INTCODE_INTERPRETER_HPP_
#include <variant>
#include <concepts>
#include <intcode/Machine.hpp>
#include <Overload.hpp>
@@ -27,19 +28,22 @@ struct BadInstruction : public std::runtime_error {
explicit BadInstruction(char const* what);
};
template <class Fin, class Fout>
template <std::invocable<ValueType&> Fin, std::invocable<ValueType> Fout, std::invocable<> Fhalt>
auto Advance(Machine & machine, Fin input, Fout output, Fhalt halt) {
return std::visit(overloaded{
[&](Halt) { return halt(); },
[&](Input i) { return input(i.pos); },
[&](Output o) { return output(o.val); },
}, Step(machine));
}
template <std::invocable<> Fin, std::invocable<ValueType> Fout>
auto Run(Machine & machine, Fin input, Fout output) -> void {
while (std::visit(overloaded{
[](Halt) { return false; },
[&](Input arg) {
arg.pos = input();
return true;
},
[&](Output arg) {
output(arg.val);
return true;
}},
Step(machine)));
while (Advance(machine,
[&](ValueType &i) { i = input(); return true; },
[&](ValueType o) { output(o); return true; },
[]() { return false; }
)) {}
}
} // namespace