aocpp/lib/include/intcode/Interpreter.hpp

48 lines
862 B
C++

#ifndef INTCODE_INTERPRETER_HPP_
#define INTCODE_INTERPRETER_HPP_
#include <variant>
#include <intcode/Machine.hpp>
#include <Overload.hpp>
namespace intcode {
struct Input {
ValueType &pos;
};
struct Output {
ValueType val;
};
struct Halt {};
auto StepInput(Machine & m, ValueType input) -> void;
auto StepOutput(Machine & m) -> ValueType;
auto Step(Machine & m) -> std::variant<Input, Output, Halt>;
struct BadInstruction : public std::runtime_error {
explicit BadInstruction(char const* what);
};
template <class Fin, class 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)));
}
} // namespace
#endif