<?php


namespace Mainto\RpcServer\Util\Reader;



use Mainto\RpcServer\Util\IO\Reader;

class LimitReader implements Reader {
    /**
     * @var Reader
     */
    public Reader $reader;
    public int $n; // 剩余可读

    public function __construct (Reader $reader, int $size) {
        $this->reader = $reader;
        $this->n = $size;
    }

    public function read (int $size): ?string {
        if ($size > $this->n) {
            $size = $this->n;
        }

        if ($size === 0) {
            return null;
        }

        $read = $this->reader->read($size);
        if ($read === null) {
            return null;
        }

        $this->n -= strlen($read);

        return $read;
    }
}