Skip to content

Commit

Permalink
Merge pull request #5 from genkgo/single_gz_stream
Browse files Browse the repository at this point in the history
use a single gz stream by encoding chunks
  • Loading branch information
frederikbosch committed Jan 7, 2021
2 parents bddd7e1 + 92c40ad commit 9081c6a
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/TarGzReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ public function __construct(TarReader $tarReader, int $level = -1)
*/
public function read(int $blockSize): \Generator
{
$deflateContext = \deflate_init(\ZLIB_ENCODING_GZIP, ['level' => $this->level]);
if ($deflateContext === false) {
throw new \UnexpectedValueException('Cannot open deflate context');
}

$generator = $this->tarReader->read($blockSize);
foreach ($generator as $stream) {
while ($stream->eof() === false) {
Expand All @@ -43,16 +48,28 @@ public function read(int $blockSize): \Generator
throw new \UnexpectedValueException('Failed to read tar stream');
}

$encoded = \gzencode($data, $this->level);
if (!$encoded) {
$encoded = \deflate_add($deflateContext, $data, \ZLIB_NO_FLUSH);
if ($encoded === false) {
throw new \UnexpectedValueException('Failed to encode tar data');
}

$stream = new \SplTempFileObject();
$stream->fwrite($encoded);
$stream->rewind();
yield $stream;
if ($encoded !== '') {
$stream = new \SplTempFileObject();
$stream->fwrite($encoded);
$stream->rewind();
yield $stream;
}
}
}

$encoded = \deflate_add($deflateContext, '', \ZLIB_FINISH);
if ($encoded === false) {
throw new \UnexpectedValueException('Failed to encode last chunk of tar data');
}

$stream = new \SplTempFileObject();
$stream->fwrite($encoded);
$stream->rewind();
yield $stream;
}
}

0 comments on commit 9081c6a

Please sign in to comment.