1111 * @see https://github.com/kjdev/php-ext-zstd
1212 */
1313class ZStandardInputStream implements InputStream {
14- private $ in ;
15- private $ buffer = null , $ position = 0 ;
14+ private $ in , $ handle ;
1615
1716 /**
1817 * Creates a new compressing output stream
@@ -21,24 +20,7 @@ class ZStandardInputStream implements InputStream {
2120 */
2221 public function __construct (InputStream $ in ) {
2322 $ this ->in = $ in ;
24- }
25-
26- /** @see https://github.com/kjdev/php-ext-zstd/issues/64 */
27- private function buffer () {
28- if (null === $ this ->buffer ) {
29- $ compressed = '' ;
30- while ($ this ->in ->available ()) {
31- $ compressed .= $ this ->in ->read ();
32- }
33-
34- $ this ->buffer = zstd_uncompress ($ compressed );
35- if (false === $ this ->buffer ) {
36- $ e = new IOException ('Failed to uncompress ' );
37- \xp::gc (__FILE__ );
38- throw $ e ;
39- }
40- }
41- return $ this ->buffer ;
23+ $ this ->handle = zstd_uncompress_init ();
4224 }
4325
4426 /**
@@ -48,9 +30,13 @@ private function buffer() {
4830 * @return string
4931 */
5032 public function read ($ limit = 8192 ) {
51- $ chunk = substr ($ this ->buffer (), $ this ->position , $ limit );
52- $ this ->position += strlen ($ chunk );
53- return $ chunk ;
33+ $ bytes = zstd_uncompress_add ($ this ->handle , $ this ->in ->read ($ limit ));
34+ if (false === $ bytes ) {
35+ $ e = new IOException ('Failed to uncompress ' );
36+ \xp::gc (__FILE__ );
37+ throw $ e ;
38+ }
39+ return $ bytes ;
5440 }
5541
5642 /**
@@ -60,7 +46,7 @@ public function read($limit= 8192) {
6046 * @return int
6147 */
6248 public function available () {
63- return strlen ( $ this ->buffer ()) - $ this -> position ;
49+ return $ this ->in -> available () ;
6450 }
6551
6652 /**
@@ -69,8 +55,10 @@ public function available() {
6955 * @return void
7056 */
7157 public function close () {
72- $ this ->buffer = null ;
73- $ this ->in ->close ();
58+ if ($ this ->handle ) {
59+ $ this ->handle = null ;
60+ $ this ->in ->close ();
61+ }
7462 }
7563
7664 /**
0 commit comments