58 lines
1.3 KiB
C++
58 lines
1.3 KiB
C++
#include <intcode/Machine.hpp>
|
|
|
|
namespace intcode {
|
|
|
|
Machine::Machine() : rom_{}, ram_{}, pc_{0}, base_{0} {}
|
|
|
|
Machine::Machine(std::vector<ValueType> program)
|
|
: rom_{std::move(program)}, ram_{}, pc_{0}, base_{0} {}
|
|
|
|
auto Machine::At(std::size_t const i) -> ValueType & {
|
|
return i < rom_.size() ? rom_[i] : ram_[i];
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
auto Machine::Rel(std::size_t const i) -> ValueType & {
|
|
return At(base_ + i);
|
|
}
|
|
|
|
auto Machine::Rel(std::size_t const i) const -> ValueType {
|
|
return At(base_ + i);
|
|
}
|
|
|
|
auto Machine::Rebase(std::size_t const offset) -> void {
|
|
base_ += offset;
|
|
}
|
|
|
|
auto Machine::Next() -> ValueType & {
|
|
return At(pc_++);
|
|
}
|
|
|
|
auto Machine::Goto(std::size_t const address) -> void {
|
|
pc_ = address;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
} // namespace
|