aocpp/lib/include/intcode/Interpreter.hpp

44 lines
763 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 {};
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