From 91a1be15c2312e268c04d1a39e78f93ef7524dda Mon Sep 17 00:00:00 2001
From: Alex Kocharin <alex@kocharin.ru>
Date: Fri, 10 Jun 2022 16:52:57 +0300
Subject: [PATCH] Fix deflate stored bug when pulling last block from window.

https://github.com/madler/zlib/commit/4c7c90768308587884fab6159d93a4695a5ab1f0
---
 lib/zlib/deflate.js | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/lib/zlib/deflate.js b/lib/zlib/deflate.js
index efd7ea8..0c5fc1c 100644
--- a/lib/zlib/deflate.js
+++ b/lib/zlib/deflate.js
@@ -517,9 +517,6 @@ const deflate_stored = (s, flush) => {
     if (len > have) {
       len = have;             /* limit len to the output */
     }
-    if (left > len) {
-      left = len;             /* limit window pull to len */
-    }
 
     /* If the stored block would be less than min_block in length, or if
      * unable to copy all of the available input when flushing, then try
@@ -528,14 +525,14 @@ const deflate_stored = (s, flush) => {
      */
     if (len < min_block && ((len === 0 && flush !== Z_FINISH) ||
                         flush === Z_NO_FLUSH ||
-                        len - left !== s.strm.avail_in)) {
+                        len !== left + s.strm.avail_in)) {
       break;
     }
 
     /* Make a dummy stored block in pending to get the header bytes,
      * including any pending bits. This also updates the debugging counts.
      */
-    last = flush === Z_FINISH && len - left === s.strm.avail_in ? 1 : 0;
+    last = flush === Z_FINISH && len === left + s.strm.avail_in ? 1 : 0;
     _tr_stored_block(s, 0, 0, last);
 
     /* Replace the lengths in the dummy stored block with len. */
@@ -547,14 +544,17 @@ const deflate_stored = (s, flush) => {
     /* Write the stored block header bytes. */
     flush_pending(s.strm);
 
-    /* Update debugging counts for the data about to be copied. */
 //#ifdef ZLIB_DEBUG
+//    /* Update debugging counts for the data about to be copied. */
 //    s->compressed_len += len << 3;
 //    s->bits_sent += len << 3;
 //#endif
 
     /* Copy uncompressed bytes from the window to next_out. */
     if (left) {
+      if (left > len) {
+        left = len;
+      }
       //zmemcpy(s->strm->next_out, s->window + s->block_start, left);
       s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);
       s.strm.next_out += left;