Skip to content

Commit 6ba57f7

Browse files
committed
lib/uzlib: For matches of the same length, take the closest one.
Signed-off-by: Damien George <[email protected]>
1 parent e182f38 commit 6ba57f7

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

lib/uzlib/lz77.c

+6-2
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,13 @@ void uzlib_lz77_init(uzlib_lz77_state_t *state, uint8_t *hist, size_t hist_max)
2828
state->hist_len = 0;
2929
}
3030

31-
// Push the given byte to the history.
3231
// Search back in the history for the maximum match of the given src data,
3332
// with support for searching beyond the end of the history and into the src buffer
3433
// (effectively the history and src buffer are concatenated).
3534
static size_t uzlib_lz77_search_max_match(uzlib_lz77_state_t *state, const uint8_t *src, size_t len, size_t *longest_offset) {
3635
size_t longest_len = 0;
3736
for (size_t hist_search = 0; hist_search < state->hist_len; ++hist_search) {
37+
// Search for a match.
3838
size_t match_len;
3939
for (match_len = 0; match_len <= MATCH_LEN_MAX && match_len < len; ++match_len) {
4040
uint8_t hist;
@@ -47,7 +47,11 @@ static size_t uzlib_lz77_search_max_match(uzlib_lz77_state_t *state, const uint8
4747
break;
4848
}
4949
}
50-
if (match_len >= MATCH_LEN_MIN && match_len > longest_len) {
50+
51+
// Take this match if its length is at least the minimum, and larger than previous matches.
52+
// If the length is the same as the previous longest then take this match as well, because
53+
// this match will be closer (more recent in the history) and take less bits to encode.
54+
if (match_len >= MATCH_LEN_MIN && match_len >= longest_len) {
5155
longest_len = match_len;
5256
*longest_offset = state->hist_len - hist_search;
5357
}

0 commit comments

Comments
 (0)