2022-11-04 09:38:01 -07:00
|
|
|
#include <intcode/Machine.hpp>
|
|
|
|
|
|
|
|
namespace intcode {
|
|
|
|
|
|
|
|
Machine::Machine() : rom_{}, ram_{}, pc_{0}, base_{0} {}
|
|
|
|
|
2022-11-06 21:12:30 -08:00
|
|
|
Machine::Machine(std::vector<ValueType> program)
|
2022-11-07 17:19:17 -08:00
|
|
|
: rom_{std::move(program)}, ram_{}, pc_{0}, base_{0} {}
|
2022-11-04 09:38:01 -07:00
|
|
|
|
2022-11-07 17:19:17 -08:00
|
|
|
auto Machine::At(std::size_t const i) -> ValueType & {
|
2022-11-04 09:38:01 -07:00
|
|
|
return i < rom_.size() ? rom_[i] : ram_[i];
|
|
|
|
}
|
|
|
|
|
2022-11-12 21:22:07 -08:00
|
|
|
auto Machine::At(std::size_t const i) const -> ValueType {
|
|
|
|
if (i < rom_.size()) return rom_[i];
|
|
|
|
if (auto it = ram_.find(i); it != ram_.end()) { return it->second; }
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-11-07 17:19:17 -08:00
|
|
|
auto Machine::Rel(std::size_t const i) -> ValueType & {
|
2022-11-04 09:38:01 -07:00
|
|
|
return At(base_ + i);
|
|
|
|
}
|
|
|
|
|
2022-11-13 11:42:40 -08:00
|
|
|
auto Machine::Rel(std::size_t const i) const -> ValueType {
|
|
|
|
return At(base_ + i);
|
|
|
|
}
|
|
|
|
|
2022-11-07 17:19:17 -08:00
|
|
|
auto Machine::Rebase(std::size_t const offset) -> void {
|
2022-11-04 09:38:01 -07:00
|
|
|
base_ += offset;
|
|
|
|
}
|
|
|
|
|
|
|
|
auto Machine::Next() -> ValueType & {
|
|
|
|
return At(pc_++);
|
|
|
|
}
|
|
|
|
|
2022-11-07 17:19:17 -08:00
|
|
|
auto Machine::Goto(std::size_t const address) -> void {
|
2022-11-04 09:38:01 -07:00
|
|
|
pc_ = address;
|
|
|
|
}
|
|
|
|
|
2022-11-13 11:42:40 -08:00
|
|
|
auto Machine::Dump() const -> std::vector<ValueType> {
|
|
|
|
if (ram_.empty()) { return rom_; }
|
|
|
|
|
|
|
|
std::size_t size = rom_.size();
|
|
|
|
for (auto const& [k,v] : ram_) {
|
|
|
|
if (k >= size) { size = k+1; }
|
|
|
|
}
|
|
|
|
|
|
|
|
std::vector<ValueType> result(size);
|
|
|
|
std::copy(rom_.begin(), rom_.end(), result.begin());
|
|
|
|
for (auto const& [k,v] : ram_) {
|
|
|
|
result[k] = v;
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2022-11-04 09:38:01 -07:00
|
|
|
} // namespace
|