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