]> wimlib.net Git - wimlib/blob - src/lz77.c
Allow in-place overwrites when unmounting read-write mounted WIM
[wimlib] / src / lz77.c
1 /*
2  * lz.c
3  *
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).
7  */
8
9 /*
10  * Copyright (C) 2012 Eric Biggers
11  * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
12  *
13  * This file is part of wimlib, a library for working with WIM files.
14  *
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)
18  * any later version.
19  *
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
23  * details.
24  *
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/.
27  */
28
29 #include "compress.h"
30 #include <string.h>
31
32 #define LZ_MIN_MATCH 3
33
34 #define HASH_BITS       15
35 #define HASH_SIZE       (1 << HASH_BITS)
36 #define HASH_MASK       (HASH_SIZE - 1)
37
38 #if LZ_MIN_MATCH == 2
39 #       define HASH_SHIFT       8
40 #elif LZ_MIN_MATCH == 3
41 #       define HASH_SHIFT       5
42 #else
43 #error "Invalid LZ_MIN_MATCH"
44 #endif
45
46 /* Hash function, based on code from zlib.  This function will update and return
47  * the hash value @hash for the string ending on the additional input character
48  * @c.  This function must be called for each consecutive character, because it
49  * uses a running hash value rather than computing it separately for each
50  * 3-character string.
51  *
52  * The AND operation guarantees that only 3 characters will affect the hash
53  * value, so every identical 3-character string will have the same hash value.
54  */
55 static inline uint update_hash(uint hash, u8 c)
56 {
57         return ((hash << HASH_SHIFT) ^ c) & HASH_MASK;
58 }
59
60
61 /* Insert a 3-character string at position @str_pos in @window and with hash
62  * code @hash into the hash table described by @hash_tab and @prev_tab.  Based
63  * on code from zlib.
64  *
65  * The hash table uses chains (linked lists) for the hash buckets, but there are
66  * no real pointers involved.  Indexing `hash_tab' by hash value gives the index
67  * within the window of the last string in the hash bucket.  To find the index
68  * of the previous string in the hash chain, the `prev_tab' array is indexed by
69  * the string index.  `prev_tab' can be indexed repeatedly by the string index
70  * to walk through the hash chain, until the special index `0' is reached,
71  * indicating the end of the hash chain.
72  */
73 static inline uint insert_string(u16 hash_tab[], u16 prev_tab[],
74                                  const u8 window[], uint str_pos, uint hash)
75 {
76         hash = update_hash(hash, window[str_pos + LZ_MIN_MATCH - 1]);
77         prev_tab[str_pos] = hash_tab[hash];
78         hash_tab[hash] = str_pos;
79         return hash;
80 }
81
82
83 /*
84  * Returns the longest match for a given input position.
85  *
86  * @window:             The window of uncompressed data.
87  * @bytes_remaining:    The number of bytes remaining in the window.
88  * @strstart:           The index of the start of the string in the window that
89  *                              we are trying to find a match for.
90  * @prev_tab:           The array of prev pointers for the hash table.
91  * @cur_match:          The index of the head of the hash chain for matches
92  *                              having the hash value of the string beginning
93  *                              at index @strstart.
94  * @prev_len:           The length of the match that was found for the string
95  *                              beginning at (@strstart - 1).
96  * @match_start_ret:    A location into which the index of the start of the
97  *                              match will be returned.
98  * @params:             Parameters that affect how long the search will proceed
99  *                              before going with the best that has been found
100  *                              so far.
101  *
102  * Returns the length of the match that was found.
103  */
104 static uint longest_match(const u8 window[], uint bytes_remaining,
105                           uint strstart, const u16 prev_tab[],
106                           uint cur_match, uint prev_len,
107                           uint *match_start_ret,
108                           const struct lz_params *params)
109 {
110         uint chain_len = params->max_chain_len;
111
112         const u8 *scan = window + strstart;
113         const u8 *match;
114         uint len;
115         uint best_len = prev_len;
116         uint match_start = cur_match;
117
118         uint nice_match = min(params->nice_match, bytes_remaining);
119
120         const u8 *strend = scan + min(params->max_match, bytes_remaining);
121
122         u8 scan_end1 = scan[best_len - 1];
123         u8 scan_end = scan[best_len];
124
125
126         /* Do not waste too much time if we already have a good match: */
127         if (best_len >= params->good_match)
128                 chain_len >>= 2;
129
130         do {
131                 match = &window[cur_match];
132
133                 /* Skip to next match if the match length cannot increase or if
134                  * the match length is less than 2.  Note that the checks below
135                  * for insufficient lookahead only occur occasionally for
136                  * performance reasons.  Therefore uninitialized memory will be
137                  * accessed, and conditional jumps will be made that depend on
138                  * those values.  However the length of the match is limited to
139                  * the lookahead, so the output of deflate is not affected by
140                  * the uninitialized values.
141                  */
142
143                 if (match[best_len] != scan_end
144                     || match[best_len - 1] != scan_end1
145                     || *match != *scan
146                     || *++match != scan[1])
147                         continue;
148                 scan++;
149
150         #if 0
151                 do {
152                 } while (scan < strend && *++match == *++scan);
153         #else
154
155                 do {
156                 } while (
157                          *++match == *++scan && *++match == *++scan &&
158                          *++match == *++scan && *++match == *++scan &&
159                          *++match == *++scan && *++match == *++scan &&
160                          *++match == *++scan && *++match == *++scan &&
161                          scan < strend);
162         #endif
163                 len = match - &window[cur_match];
164
165                 scan = &window[strstart];
166
167                 if (len > best_len) {
168                         match_start = cur_match;
169                         best_len = len;
170                         if (len >= nice_match)
171                                 break;
172                         scan_end1  = scan[best_len - 1];
173                         scan_end   = scan[best_len];
174                 }
175         } while (--chain_len != 0 && (cur_match = prev_tab[cur_match]) != 0);
176         *match_start_ret = match_start;
177         return min(min(best_len, bytes_remaining), params->max_match);
178 }
179
180
181
182 /*
183  * Determines the sequence of matches and literals that a block of data will be
184  * compressed to.
185  *
186  * @uncompressed_data:  The data that is to be compressed.
187  * @uncompressed_len:   The length of @uncompressed_data, in bytes.
188  * @match_tab:          An array for the intermediate representation of matches.
189  * @record_match:       A function that will be called to produce the
190  *                              intermediate representation of a match, given
191  *                              the offset and length.  This function should also
192  *                              update the appropriate symbol frequency counts
193  *                              so that any needed Huffman codes can be made
194  *                              later.
195  * @record_literal:     A function that will be called to produce the
196  *                              intermediate representation of a literal, given
197  *                              the character of the literal.  This function
198  *                              should also update the appropriate symbol
199  *                              frequency counts so that any needed Huffman
200  *                              codes can be made later.
201  * @record_match_arg_1:
202  * @record_match_arg_2: Extra arguments to be passed to @record_match.
203  * @record_literal_arg: Extra arguments to be passed to @record_literal.
204  * @params:             Structure that contains parameters that affect how the
205  *                              analysis proceeds (mainly how good the matches
206  *                              have to be).
207  *
208  * Returns the total number of matches and literal bytes that were found; this
209  * is the number of slots in @match_tab that have been filled with the
210  * intermediate representation of a match or literal byte.
211  */
212 uint lz_analyze_block(const u8 uncompressed_data[], uint uncompressed_len,
213                       u32 match_tab[], lz_record_match_t record_match,
214                       lz_record_literal_t record_literal, void *record_match_arg1,
215                       void *record_match_arg2, void *record_literal_arg,
216                       const struct lz_params *params)
217 {
218         uint cur_match_pos = 0;
219         uint cur_input_pos = 0;
220         uint hash          = 0;
221         uint hash_head     = 0;
222         uint prev_len      = params->min_match - 1;
223         uint prev_start;
224         uint match_len     = params->min_match - 1;
225         uint match_start   = 0;
226         bool match_available = false;
227         u16 hash_tab[HASH_SIZE];
228         u32 match;
229         u16 prev_tab[uncompressed_len];
230
231         ZERO_ARRAY(hash_tab);
232         ZERO_ARRAY(prev_tab);
233
234         do {
235                 /* If there are at least 3 characters remaining in the input,
236                  * insert the 3-character string beginning at
237                  * uncompressed_data[cur_input_pos] into the hash table.
238                  *
239                  * hash_head is set to the index of the previous string in the
240                  * hash bucket, or 0 if there is no such string */
241                 if (uncompressed_len - cur_input_pos >= params->min_match) {
242                         hash = insert_string(hash_tab, prev_tab,
243                                              uncompressed_data,
244                                              cur_input_pos, hash);
245                         hash_head = prev_tab[cur_input_pos];
246                 } else {
247                         hash_head = 0;
248                 }
249
250
251                 /* Find the longest match, discarding those <= prev_len. */
252                 prev_len = match_len;
253                 prev_start = match_start;
254                 match_len = params->min_match - 1;
255
256                 if (hash_head != 0 && prev_len < params->max_lazy_match) {
257                         /* To simplify the code, we prevent matches with the
258                          * string of window index 0 (in particular we have to
259                          * avoid a match of the string with itself at the start
260                          * of the input file).  */
261                         match_len = longest_match(uncompressed_data,
262                                                   uncompressed_len - cur_input_pos,
263                                                   cur_input_pos, prev_tab,
264                                                   hash_head, prev_len,
265                                                   &match_start, params);
266
267                         if (match_len == params->min_match &&
268                              cur_input_pos - match_start > params->too_far)
269                                 match_len = params->min_match - 1;
270                 }
271
272                 /* If there was a match at the previous step and the current
273                  * match is not better, output the previous match:
274                  */
275                 if (prev_len >= params->min_match && match_len <= prev_len) {
276
277                         /* Do not insert strings in hash table beyond this. */
278                         uint max_insert = uncompressed_len - params->min_match;
279
280                         /*DEBUG("Recording match (pos = %u, offset = %u, len = %u)\n",*/
281                                         /*cur_input_pos - 1, */
282                                         /*cur_input_pos - 1 - prev_start,*/
283                                         /*prev_len);*/
284
285                         match = (*record_match)(cur_input_pos - 1 - prev_start,
286                                                 prev_len,
287                                                 record_match_arg1,
288                                                 record_match_arg2);
289
290                         match_tab[cur_match_pos++] = match;
291
292                         /* Insert in hash table all strings up to the end of the match.
293                          * strstart-1 and strstart are already inserted. If there is not
294                          * enough lookahead, the last two strings are not inserted in
295                          * the hash table.
296                          */
297 #if LZ_MIN_MATCH == 2
298                         if (prev_len >= 3)
299 #endif
300                         {
301                                 prev_len -= 2;
302
303                                 do {
304                                         if (++cur_input_pos <= max_insert) {
305                                                 hash = insert_string(hash_tab, prev_tab,
306                                                                      uncompressed_data,
307                                                                      cur_input_pos,
308                                                                      hash);
309                                         }
310                                 } while (--prev_len != 0);
311                         }
312                         match_available = false;
313                         match_len = params->min_match - 1;
314                 } else if (match_available) {
315                         /* If there was no match at the previous position, output a
316                          * single literal. If there was a match but the current match
317                          * is longer, truncate the previous match to a single literal.
318                          */
319
320                         /*DEBUG("Recording litrl (pos = %u, value = %u)\n",*/
321                                         /*cur_input_pos - 1, */
322                                         /*uncompressed_data[cur_input_pos - 1]);*/
323
324                         match = (*record_literal)(
325                                         uncompressed_data[cur_input_pos - 1],
326                                                         record_literal_arg);
327                         match_tab[cur_match_pos++] = match;
328                 } else {
329                         /* There is no previous match to compare with, wait for
330                          * the next step to decide.  */
331                         match_available = true;
332                 }
333         } while (++cur_input_pos < uncompressed_len);
334
335         if (match_available) {
336                 match = (*record_literal)(uncompressed_data[cur_input_pos - 1],
337                                                 record_literal_arg);
338                 match_tab[cur_match_pos++] = match;
339         }
340         return cur_match_pos;
341 }