aocpp/lib/include/intcode/Interpreter.hpp
2022-11-05 15:40:30 -07:00

52 lines
1.2 KiB
C++

#ifndef INTCODE_INTERPRETER_HPP_
#define INTCODE_INTERPRETER_HPP_
#include <variant>
#include <concepts>
#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 <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 (Advance(machine,
[&](ValueType &i) { i = input(); return true; },
[&](ValueType o) { output(o); return true; },
[]() { return false; }
)) {}
}
} // namespace
#endif