4 * This file provides the code to analyze a buffer of uncompressed data for
5 * matches, as per the LZ77 algorithm. It uses a hash table to accelerate the
6 * process. This is based on code from zlib (v. 1.2.5).
10 * Copyright (C) 2012 Eric Biggers
11 * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
13 * This file is part of wimlib, a library for working with WIM files.
15 * wimlib is free software; you can redistribute it and/or modify it under the
16 * terms of the GNU General Public License as published by the Free
17 * Software Foundation; either version 3 of the License, or (at your option)
20 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
21 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
22 * A PARTICULAR PURPOSE. See the GNU General Public License for more
25 * You should have received a copy of the GNU General Public License
26 * along with wimlib; if not, see http://www.gnu.org/licenses/.
33 #define HASH_SIZE (1 << HASH_BITS)
34 #define HASH_MASK (HASH_SIZE - 1)
35 #define HASH_SHIFT ((HASH_BITS + 2) / 3)
37 /* Hash function, based on code from zlib. This function will update and return
38 * the hash value @hash for the string ending on the additional input character
39 * @c. This function must be called for each consecutive character, because it
40 * uses a running hash value rather than computing it separately for each
43 * The AND operation guarantees that only 3 characters will affect the hash
44 * value, so every identical 3-character string will have the same hash value.
46 static inline uint update_hash(uint hash, u8 c)
48 return ((hash << HASH_SHIFT) ^ c) & HASH_MASK;
52 /* Insert a 3-character string at position @str_pos in @window and with hash
53 * code @hash into the hash table described by @hash_tab and @prev_tab. Based
56 * The hash table uses chains (linked lists) for the hash buckets, but there are
57 * no real pointers involved. Indexing `hash_tab' by hash value gives the index
58 * within the window of the last string in the hash bucket. To find the index
59 * of the previous string in the hash chain, the `prev_tab' array is indexed by
60 * the string index. `prev_tab' can be indexed repeatedly by the string index
61 * to walk through the hash chain, until the special index `0' is reached,
62 * indicating the end of the hash chain.
64 static inline uint insert_string(u16 hash_tab[], u16 prev_tab[],
65 const u8 window[], uint str_pos, uint hash)
67 hash = update_hash(hash, window[str_pos + 2]);
68 prev_tab[str_pos] = hash_tab[hash];
69 hash_tab[hash] = str_pos;
75 * Returns the longest match for a given input position.
77 * @window: The window of uncompressed data.
78 * @bytes_remaining: The number of bytes remaining in the window.
79 * @strstart: The index of the start of the string in the window that
80 * we are trying to find a match for.
81 * @prev_tab: The array of prev pointers for the hash table.
82 * @cur_match: The index of the head of the hash chain for matches
83 * having the hash value of the string beginning
85 * @prev_len: The length of the match that was found for the string
86 * beginning at (@strstart - 1).
87 * @match_start_ret: A location into which the index of the start of the
88 * match will be returned.
89 * @params: Parameters that affect how long the search will proceed
90 * before going with the best that has been found
93 * Returns the length of the match that was found.
95 static uint longest_match(const u8 window[], uint bytes_remaining,
96 uint strstart, const u16 prev_tab[],
97 uint cur_match, uint prev_len,
98 uint *match_start_ret,
99 const struct lz_params *params)
101 uint chain_len = params->max_chain_len;
103 const u8 *scan = window + strstart;
106 uint best_len = prev_len;
107 uint match_start = cur_match;
109 uint nice_match = min(params->nice_match, bytes_remaining);
111 const u8 *strend = scan + params->max_match;
113 u8 scan_end1 = scan[best_len - 1];
114 u8 scan_end = scan[best_len];
117 /* Do not waste too much time if we already have a good match: */
118 if (best_len >= params->good_match)
122 match = &window[cur_match];
125 /* Skip to next match if the match length cannot increase
126 * or if the match length is less than 2. Note that the checks below
127 * for insufficient lookahead only occur occasionally for performance
128 * reasons. Therefore uninitialized memory will be accessed, and
129 * conditional jumps will be made that depend on those values.
130 * However the length of the match is limited to the lookahead, so
131 * the output of deflate is not affected by the uninitialized values.
134 if (match[best_len] != scan_end ||
135 match[best_len-1] != scan_end1 ||
137 *++match != scan[1]) continue;
139 /* The check at best_len-1 can be removed because it will be made
140 * again later. (This heuristic is not always a win.)
141 * It is not necessary to compare scan[2] and match[2] since they
142 * are always equal when the other bytes match, given that
143 * the hash keys are equal and that HASH_BITS >= 8.
147 wimlib_assert(*scan == *match);
149 /* We check for insufficient lookahead only every 8th comparison;
150 * the 256th check will be made at strstart+258. */
152 } while (*++scan == *++match && *++scan == *++match &&
153 *++scan == *++match && *++scan == *++match &&
154 *++scan == *++match && *++scan == *++match &&
155 *++scan == *++match && *++scan == *++match &&
158 len = params->max_match - (int)(strend - scan);
159 scan = strend - params->max_match;
161 if (len > best_len) {
162 match_start = cur_match;
164 if (len >= nice_match)
166 scan_end1 = scan[best_len - 1];
167 scan_end = scan[best_len];
169 cur_match = prev_tab[cur_match];
170 } while (--chain_len != 0 && cur_match != 0);
171 *match_start_ret = match_start;
172 return min(min(best_len, bytes_remaining), params->max_match);
178 * Determines the sequence of matches and literals that a block of data will be
181 * @uncompressed_data: The data that is to be compressed.
182 * @uncompressed_len: The length of @uncompressed_data, in bytes.
183 * @match_tab: An array for the intermediate representation of matches.
184 * @record_match: A function that will be called to produce the
185 * intermediate representation of a match, given
186 * the offset and length. This function should also
187 * update the appropriate symbol frequency counts
188 * so that any needed Huffman codes can be made
190 * @record_literal: A function that will be called to produce the
191 * intermediate representation of a literal, given
192 * the character of the literal. This function
193 * should also update the appropriate symbol
194 * frequency counts so that any needed Huffman
195 * codes can be made later.
196 * @record_match_arg_1:
197 * @record_match_arg_2: Extra arguments to be passed to @record_match.
198 * @record_literal_arg: Extra arguments to be passed to @record_literal.
199 * @params: Structure that contains parameters that affect how the
200 * analysis proceeds (mainly how good the matches
203 * Returns the total number of matches and literal bytes that were found; this
204 * is the number of slots in @match_tab that have been filled with the
205 * intermediate representation of a match or literal byte.
207 uint lz_analyze_block(const u8 uncompressed_data[], uint uncompressed_len,
208 u32 match_tab[], lz_record_match_t record_match,
209 lz_record_literal_t record_literal, void *record_match_arg1,
210 void *record_match_arg2, void *record_literal_arg,
211 const struct lz_params *params)
213 uint cur_match_pos = 0;
214 uint cur_input_pos = 0;
217 uint prev_len = params->min_match - 1;
219 uint match_len = params->min_match - 1;
220 uint match_start = 0;
221 bool match_available = false;
222 u16 hash_tab[HASH_SIZE];
224 u16 prev_tab[uncompressed_len];
226 ZERO_ARRAY(hash_tab);
227 ZERO_ARRAY(prev_tab);
230 /* If there are at least 3 characters remaining in the input,
231 * insert the 3-character string beginning at
232 * uncompressed_data[cur_input_pos] into the hash table.
234 * hash_head is set to the index of the previous string in the
235 * hash bucket, or 0 if there is no such string */
236 if (uncompressed_len - cur_input_pos >= params->min_match) {
237 hash = insert_string(hash_tab, prev_tab,
239 cur_input_pos, hash);
240 hash_head = prev_tab[cur_input_pos];
246 /* Find the longest match, discarding those <= prev_len. */
247 prev_len = match_len;
248 prev_start = match_start;
249 match_len = params->min_match - 1;
251 if (hash_head != 0 && prev_len < params->max_lazy_match) {
252 /* To simplify the code, we prevent matches with the
253 * string of window index 0 (in particular we have to
254 * avoid a match of the string with itself at the start
255 * of the input file). */
256 match_len = longest_match(uncompressed_data,
257 uncompressed_len - cur_input_pos,
258 cur_input_pos, prev_tab,
260 &match_start, params);
262 if (match_len == params->min_match &&
263 cur_input_pos - match_start > params->too_far)
265 match_len = params->min_match - 1;
269 /* If there was a match at the previous step and the current
270 * match is not better, output the previous match:
272 if (prev_len >= params->min_match && match_len <= prev_len) {
274 /* Do not insert strings in hash table beyond this. */
275 uint max_insert = uncompressed_len - params->min_match;
277 /*DEBUG("Recording match (pos = %u, offset = %u, len = %u)\n",*/
278 /*cur_input_pos - 1, */
279 /*cur_input_pos - 1 - prev_start,*/
282 match = (*record_match)(cur_input_pos - 1 - prev_start,
287 match_tab[cur_match_pos++] = match;
289 /* Insert in hash table all strings up to the end of the match.
290 * strstart-1 and strstart are already inserted. If there is not
291 * enough lookahead, the last two strings are not inserted in
297 if (++cur_input_pos <= max_insert) {
298 hash = insert_string(hash_tab, prev_tab,
303 } while (--prev_len != 0);
305 match_available = false;
306 match_len = params->min_match - 1;
307 } else if (match_available) {
308 /* If there was no match at the previous position, output a
309 * single literal. If there was a match but the current match
310 * is longer, truncate the previous match to a single literal.
313 /*DEBUG("Recording litrl (pos = %u, value = %u)\n",*/
314 /*cur_input_pos - 1, */
315 /*uncompressed_data[cur_input_pos - 1]);*/
317 match = (*record_literal)(
318 uncompressed_data[cur_input_pos - 1],
320 match_tab[cur_match_pos++] = match;
322 /* There is no previous match to compare with, wait for
323 * the next step to decide. */
324 match_available = true;
326 } while (++cur_input_pos < uncompressed_len);
328 if (match_available) {
329 match = (*record_literal)(uncompressed_data[cur_input_pos - 1],
331 match_tab[cur_match_pos++] = match;
333 return cur_match_pos;