aocpp/lib/include/intcode/Interpreter.hpp

48 lines
862 B
C++
Raw Normal View History

2022-11-04 09:38:01 -07:00
#ifndef INTCODE_INTERPRETER_HPP_
#define INTCODE_INTERPRETER_HPP_
2022-11-04 11:36:30 -07:00
#include <variant>
2022-11-04 09:38:01 -07:00
2022-11-04 11:36:30 -07:00
#include <intcode/Machine.hpp>
#include <Overload.hpp>
2022-11-04 09:38:01 -07:00
namespace intcode {
struct Input {
ValueType &pos;
};
struct Output {
ValueType val;
};
struct Halt {};
2022-11-05 15:06:54 -07:00
auto StepInput(Machine & m, ValueType input) -> void;
auto StepOutput(Machine & m) -> ValueType;
2022-11-04 09:38:01 -07:00
auto Step(Machine & m) -> std::variant<Input, Output, Halt>;
struct BadInstruction : public std::runtime_error {
explicit BadInstruction(char const* what);
};
2022-11-04 11:36:30 -07:00
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)));
}
2022-11-04 09:38:01 -07:00
} // namespace
#endif