MadelineProto/src/danog/MadelineProto/Stream/Common/SimpleBufferedRawStream.php

78 lines
2.6 KiB
PHP
Raw Normal View History

2019-06-25 17:11:37 +02:00
<?php
2020-01-31 19:29:43 +01:00
2019-06-25 17:11:37 +02:00
/**
* Buffered raw stream.
*
* This file is part of MadelineProto.
* MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU General Public License along with MadelineProto.
* If not, see <http://www.gnu.org/licenses/>.
*
* @author Daniil Gentili <daniil@daniil.it>
2020-02-17 14:13:46 +01:00
* @copyright 2016-2020 Daniil Gentili <daniil@daniil.it>
2019-06-25 17:11:37 +02:00
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
*
2019-10-31 15:07:35 +01:00
* @link https://docs.madelineproto.xyz MadelineProto documentation
2019-06-25 17:11:37 +02:00
*/
namespace danog\MadelineProto\Stream\Common;
use danog\MadelineProto\Stream\BufferedStreamInterface;
use danog\MadelineProto\Stream\BufferInterface;
use danog\MadelineProto\Stream\RawStreamInterface;
/**
2020-10-26 21:38:23 +01:00
* Buffered raw stream, that simply returns less data on EOF instead of throwing.
2019-06-25 17:11:37 +02:00
*
* @author Daniil Gentili <daniil@daniil.it>
*/
class SimpleBufferedRawStream extends BufferedRawStream implements BufferedStreamInterface, BufferInterface, RawStreamInterface
{
/**
* Read data asynchronously.
*
* @param int $length Amount of data to read
*
* @return \Generator
*/
2019-10-29 21:33:23 +01:00
public function bufferReadGenerator(int $length): \Generator
2019-06-25 17:11:37 +02:00
{
2019-09-02 17:08:36 +02:00
$size = \fstat($this->memory_stream)['size'];
$offset = \ftell($this->memory_stream);
2019-06-25 17:11:37 +02:00
$buffer_length = $size - $offset;
if ($buffer_length < $length && $buffer_length) {
2019-09-02 17:08:36 +02:00
\fseek($this->memory_stream, $offset + $buffer_length);
2019-06-25 17:11:37 +02:00
}
while ($buffer_length < $length) {
$chunk = yield $this->read();
if ($chunk === null) {
break;
}
2019-09-02 17:08:36 +02:00
\fwrite($this->memory_stream, $chunk);
$buffer_length += \strlen($chunk);
2019-06-25 17:11:37 +02:00
}
2019-09-02 17:08:36 +02:00
\fseek($this->memory_stream, $offset);
return \fread($this->memory_stream, $length);
2019-06-25 17:11:37 +02:00
}
2019-12-14 13:58:04 +01:00
/**
* {@inheritDoc}
*
* @return RawStreamInterface
*/
public function getStream(): RawStreamInterface
{
return $this->stream;
}
2019-06-25 17:11:37 +02:00
/**
* Get class name.
*
* @return string
*/
public static function getName(): string
{
return __CLASS__;
}
}