public function read(int $length = 8192) : Awaitable
{
if (!$this->readerEnabled) {
$len = \strlen($this->readBuffer);
try {
$chunk = $this->fillReadBuffer($len, $length);
} catch (\Throwable $e) {
return new Failure($e);
}
if ($chunk === null) {
return new Success(null);
}
if ($chunk !== $this) {
if ($len > $length) {
$this->readBuffer = \substr($chunk, $length);
return new Success(\substr($chunk, 0, $length));
}
$this->readBuffer = '';
return new Success($chunk);
}
$this->readerEnabled = true;
if ($this->pendingReads === null) {
$this->pendingReads = new \SplQueue();
}
if ($this->readWatcher === null) {
$this->readWatcher = Loop::onReadable($this->socket, $this->createReadWatcher());
} else {
try {
Loop::enable($this->readWatcher);
} catch (InvalidWatcherException $e) {
$this->readWatcher = Loop::onReadable($this->socket, $this->createReadWatcher());
}
}
}
$this->pendingReads->enqueue($read = new PendingRead($length, function () {
foreach ($this->pendingReads as $read) {
if (!$read->disabled) {
return;
}
}
$this->readerEnabled = false;
Loop::disable($this->readWatcher);
}));
return $read;
}