philips-cnc6600-interpreter/src/Machine/Memory/MemoryController.php

83 lines
1.4 KiB
PHP

<?php
namespace Machine\Memory;
use Countable;
use InvalidArgumentException;
use Program\Block;
use RuntimeException;
class MemoryController implements Countable
{
private ProgramMemory $memory;
public ?int $N = null;
/** @var Block[]|null */
private ?array $blockBuffer;
private int $index;
public function __construct(ProgramMemory $memory)
{
$this->memory = $memory;
$this->blockBuffer = null;
}
public function loadProgram(int $N): void
{
$program = $this->memory->read($N);
if (!$program) {
throw new InvalidArgumentException("Program N{$N} not found");
}
$this->N = $N;
$this->blockBuffer = $program->getIterator()->getArrayCopy();
$this->index = 0;
}
public function reset(): void
{
$this->N = null;
$this->blockBuffer = null;
$this->index = 0;
}
public function count()
{
return count($this->blockBuffer) - $this->index;
}
public function previous(): ?Block
{
$this->guardNoProgramLoaded();
$block = $this->blockBuffer[$this->index--];
return $block ? clone $block : null;
}
public function next(): ?Block
{
$this->guardNoProgramLoaded();
$block = $this->blockBuffer[$this->index++];
return $block ? clone $block : null;
}
public function ready(): bool
{
return $this->count() > 0;
}
private function guardNoProgramLoaded(): void
{
if (is_null($this->blockBuffer)) {
throw new RuntimeException('No program loaded in memory');
}
}
}