aocpp/lib/include/intcode.hpp

65 lines
1.4 KiB
C++
Raw Normal View History

2022-11-03 08:15:17 -07:00
#ifndef INTCODE_HPP_
#define INTCODE_HPP_
#include <cstddef>
#include <cstdint>
2022-11-03 12:53:10 -07:00
#include <istream>
2022-11-03 08:15:17 -07:00
#include <unordered_map>
2022-11-03 14:43:47 -07:00
#include <stdexcept>
2022-11-03 12:53:10 -07:00
#include <variant>
#include <vector>
2022-11-03 08:15:17 -07:00
2022-11-03 12:53:10 -07:00
template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template <class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
2022-11-03 08:15:17 -07:00
2022-11-03 12:53:10 -07:00
namespace intcode {
2022-11-03 08:15:17 -07:00
2022-11-03 14:43:47 -07:00
using ValueType = std::int64_t;
2022-11-03 08:15:17 -07:00
2022-11-03 12:53:10 -07:00
struct Input {
2022-11-03 14:43:47 -07:00
ValueType &pos;
2022-11-03 12:53:10 -07:00
};
2022-11-03 08:15:17 -07:00
2022-11-03 12:53:10 -07:00
struct Output {
2022-11-03 14:43:47 -07:00
ValueType val;
2022-11-03 12:53:10 -07:00
};
2022-11-03 08:15:17 -07:00
2022-11-03 12:53:10 -07:00
struct Halt {};
2022-11-03 08:15:17 -07:00
2022-11-03 12:53:10 -07:00
class Machine {
2022-11-03 14:43:47 -07:00
std::vector<ValueType> rom_;
std::unordered_map<std::size_t, ValueType> ram_;
2022-11-03 12:53:10 -07:00
std::size_t pc_;
std::size_t base_;
2022-11-03 08:15:17 -07:00
public:
2022-11-03 12:53:10 -07:00
Machine();
2022-11-03 14:43:47 -07:00
explicit Machine(std::vector<ValueType> ram);
/// Access memory at absolute address
/// @param address
/// @return reference to memory at given address
auto At(std::size_t address) -> ValueType &;
2022-11-03 12:53:10 -07:00
2022-11-03 14:43:47 -07:00
/// Access memory at address relative to base pointer
/// @param offset from base pointer
/// @return reference to memory at given offset
auto Rel(std::size_t offset) -> ValueType &;
2022-11-04 08:29:02 -07:00
auto Next() -> ValueType &;
auto Goto(std::size_t address) -> void;
auto Rebase(std::size_t offset) -> void;
2022-11-03 08:15:17 -07:00
};
2022-11-04 08:29:02 -07:00
auto Step(Machine & m) -> std::variant<Input, Output, Halt>;
2022-11-03 14:43:47 -07:00
struct BadInstruction : public std::runtime_error {
explicit BadInstruction(char const* what);
2022-11-03 12:53:10 -07:00
};
2022-11-03 14:43:47 -07:00
auto ParseStream(std::istream &in) -> std::vector<ValueType>;
2022-11-03 12:53:10 -07:00
}
2022-11-03 08:15:17 -07:00
2022-11-03 12:53:10 -07:00
#endif // INTCODE_HPP_