From 7af6320ad78b390de42f414fabdc64dc6d67a5ea Mon Sep 17 00:00:00 2001
From: Mark Adler <madler@alumni.caltech.edu>
Date: Fri, 19 Jan 2024 12:19:53 -0800
Subject: [PATCH] Fix a bug in ZLIB_DEBUG compiles in check_match().

This avoids trying to compare a match starting one byte before the
current window. Thanks to @zmodem (Hans) for discovering this.

Reference:https://github.com/madler/zlib/commit/7af6320ad78b390de42f414fabdc64dc6d67a5ea
Conflict: Patch context adaptation

---
 deflate.c | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)

diff --git a/deflate.c b/deflate.c
index 8088083..396ab12 100644
--- a/deflate.c
+++ b/deflate.c
@@ -1510,13 +1510,21 @@ local void check_match(s, start, match, length)
     int length;
 {
     /* check that the match is indeed a match */
-    if (zmemcmp(s->window + match,
-                s->window + start, length) != EQUAL) {
-        fprintf(stderr, " start %u, match %u, length %d\n",
-                start, match, length);
+    Bytef *back = s->window + (int)match, *here = s->window + start;
+    IPos len = length;
+    if (match == (IPos)-1) {
+        /* match starts one byte before the current window -- just compare the
+           subsequent length-1 bytes */
+        back++;
+        here++;
+        len--;
+    }
+    if (zmemcmp(back, here, len) != EQUAL) {
+        fprintf(stderr, " start %u, match %d, length %d\n",
+                start, (int)match, length);
         do {
-            fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
-        } while (--length != 0);
+            fprintf(stderr, "(%02x %02x)", *back++, *here++);
+        } while (--len != 0);
         z_error("invalid match");
     }
     if (z_verbose > 1) {
-- 
2.33.0

