<?php


namespace Mainto\RpcServer\Util\IO;


class ReadBuffer implements Reader {
    private Reader $r;

    private ?string $buf = "";
    private int $bufSize = 0;
    private int $bufUsedSize = 0;

    /**
     * 每次读取的大小
     *
     * @var int
     */
    private int $readBufSize;

    public function __construct (Reader $r, int $readSize) {
        $this->r = $r;
        $this->readBufSize = $readSize;
    }

    public function read (int $size): ?string {
        if ($size === 0) {
            return null;
        }

        $res = "";
        $currentReadSize = 0;

        while (true) {
            if ($this->bufUsedSize === $this->bufSize) {
                $this->buf = $this->r->read($this->readBufSize);
                $this->bufSize = strlen($this->buf);
                if ($this->bufSize === 0) {
                    return "";
                }
                $this->bufUsedSize = 0;
            }

            $append = substr($this->buf, $this->bufUsedSize, $this->bufSize > ($size - $currentReadSize) ? $size - $currentReadSize : $this->bufSize);
            $copySize = strlen($append);
            $res .= $append;

            $this->bufUsedSize += $copySize;
            $currentReadSize += $copySize;

            if ($currentReadSize == $size) {
                return $res;
            }
        }
    }
}