<?php


namespace Mainto\RpcServer\Util\Bytes;


use Mainto\RpcServer\Util\IO\Exceptions\ClosedPipeException;
use Mainto\RpcServer\Util\IO\ReadCloser;

class Reader implements ReadCloser {
    private int $offset = 0;

    private string $bytes;
    private bool $closed = false;


    public function __construct (string $bytes) {
        $this->bytes = $bytes;
    }

    private function empty() {
        return $this->offset >= strlen($this->bytes);
    }

    public function read (int $size): ?string {
        if ($this->closed) {
            throw new ClosedPipeException();
        }
        if ($this->empty()) {
            return null;
        }

        $read = substr($this->bytes, $this->offset, $size);

        $this->offset += strlen($read);

        return $read;
    }

    public function close () {
        $this->closed = true;
    }
}