aocpp/lib/include/intcode/Interpreter.hpp

52 lines
1.2 KiB
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-05 15:40:30 -07:00
#include <concepts>
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 {
2022-11-06 19:46:43 -08:00
ValueType &input;
2022-11-04 09:38:01 -07:00
};
struct Output {
2022-11-06 19:46:43 -08:00
ValueType output;
2022-11-04 09:38:01 -07:00
};
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-05 15:40:30 -07:00
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(); },
2022-11-06 19:46:43 -08:00
[&](Input i) { return input(i.input); },
[&](Output o) { return output(o.output); },
2022-11-05 15:40:30 -07:00
}, Step(machine));
}
template <std::invocable<> Fin, std::invocable<ValueType> Fout>
2022-11-04 11:36:30 -07:00
auto Run(Machine & machine, Fin input, Fout output) -> void {
2022-11-05 15:40:30 -07:00
while (Advance(machine,
[&](ValueType &i) { i = input(); return true; },
[&](ValueType o) { output(o); return true; },
[]() { return false; }
)) {}
2022-11-04 11:36:30 -07:00
}
2022-11-04 09:38:01 -07:00
} // namespace
#endif