]> wimlib.net Git - wimlib/blob - src/lz_mf.c
ee7c80d89eac39529c00dd821494104d475bcd2c
[wimlib] / src / lz_mf.c
1 /*
2  * lz_mf.c
3  *
4  * Interface for Lempel-Ziv match-finders.
5  *
6  * Copyright (c) 2014 Eric Biggers.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
26  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
28  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #ifdef HAVE_CONFIG_H
33 #  include "config.h"
34 #endif
35
36 #include "wimlib/lz_mf.h"
37 #include "wimlib/lz_mf_ops.h"
38 #include "wimlib/util.h"
39
40 /* Available match-finding algorithms.  */
41 static const struct lz_mf_ops *mf_ops[] = {
42         [LZ_MF_LCP_INTERVAL_TREE]       = &lz_lcp_interval_tree_ops,
43         [LZ_MF_LINKED_SUFFIX_ARRAY]     = &lz_linked_suffix_array_ops,
44 };
45
46 static const struct lz_mf_ops *
47 get_mf_ops(enum lz_mf_algo algorithm)
48 {
49         if ((unsigned int)algorithm >= ARRAY_LEN(mf_ops))
50                 return NULL;
51         return mf_ops[(unsigned int)algorithm];
52 }
53
54 /*
55  * Returns an upper bound on the number of bytes of memory that will be consumed
56  * by a match-finder allocated with the specified algorithm and maximum window
57  * size.
58  *
59  * The returned value does not include the size of the window itself.  The
60  * caller must account for this separately if needed.
61  *
62  * If @algorithm is invalid, returns 0.
63  */
64 u64
65 lz_mf_get_needed_memory(enum lz_mf_algo algorithm, u32 max_window_size)
66 {
67         const struct lz_mf_ops *ops;
68
69         ops = get_mf_ops(algorithm);
70         if (!ops)
71                 return 0;
72         return ops->struct_size + ops->get_needed_memory(max_window_size);
73 }
74 /*
75  * Returns %true if and only if the specified parameters can be validly used to
76  * create a match-finder using lz_mf_alloc().
77  */
78 bool
79 lz_mf_params_valid(const struct lz_mf_params *params)
80 {
81         const struct lz_mf_ops *ops;
82
83         /* Require that a valid algorithm be specified.  */
84         ops = get_mf_ops(params->algorithm);
85         if (!ops)
86                 return false;
87
88         /* Don't allow empty windows.  Otherwise, some match-finding algorithms
89          * might need special-case code to handle empty windows.  */
90         if (params->max_window_size == 0)
91                 return false;
92
93         /* Don't allow length-1 matches, so that match-finding algorithms don't
94          * need to worry about this case.  Most LZ-based compression formats
95          * don't allow length-1 matches, since they usually aren't helpful for
96          * compression.  Also, if a compressor really does need length-1
97          * matches, it can easily maintain its own table of length 256
98          * containing the most-recently-seen position for each byte value.
99          *
100          * min_match_len == 0 is valid, since that means the match-finding
101          * algorithm will fill in a default value.  */
102         if (params->min_match_len == 1)
103                 return false;
104
105         if (params->max_match_len != 0) {
106
107                 /* Don't allow length-1 matches (same reason as above).  */
108                 if (params->max_match_len == 1)
109                         return false;
110
111                 /* Don't allow the maximum match length to be shorter than the
112                  * minimum match length.  */
113                 if (params->max_match_len < params->min_match_len)
114                         return false;
115         }
116
117         /* Don't allow the needed memory size to overflow a 'size_t'.  */
118         if (sizeof(size_t) < sizeof(u64)) {
119                 u64 needed_mem = ops->get_needed_memory(params->max_window_size);
120                 if ((size_t)needed_mem != needed_mem)
121                         return false;
122         }
123
124         /* Call the algorithm-specific routine to finish the validation.  */
125         return ops->params_valid(params);
126 }
127
128 /*
129  * Allocate a new match-finder.
130  *
131  * @params
132  *      The parameters for the match-finder.  See the declaration of 'struct
133  *      lz_mf_params' for more information.
134  *
135  * Returns a pointer to the new match-finder, or NULL if out of memory or the
136  * parameters are invalid.  Call lz_mf_params_valid() beforehand to test the
137  * parameter validity separately.
138  */
139 struct lz_mf *
140 lz_mf_alloc(const struct lz_mf_params *params)
141 {
142         struct lz_mf *mf;
143         const struct lz_mf_ops *ops;
144
145         /* Validate the parameters.  */
146         if (!lz_mf_params_valid(params))
147                 return NULL;
148
149         /* Get the match-finder operations structure.  Since we just validated
150          * the parameters, this is guaranteed to return a valid structure.  */
151         ops = get_mf_ops(params->algorithm);
152         LZ_ASSERT(ops != NULL);
153
154         /* Allocate memory for the match-finder structure.  */
155         LZ_ASSERT(ops->struct_size >= sizeof(struct lz_mf));
156         mf = CALLOC(1, ops->struct_size);
157         if (!mf)
158                 return NULL;
159
160         /* Set the parameters and operations fields.  */
161         mf->params = *params;
162         mf->ops = *ops;
163
164         /* Perform algorithm-specific initialization.  Normally this is where
165          * most of the necessary memory is allocated.  */
166         if (!mf->ops.init(mf)) {
167                 FREE(mf);
168                 return NULL;
169         }
170
171         /* The algorithm must have set min_match_len and max_match_len if either
172          * was 0.  */
173         LZ_ASSERT(mf->params.min_match_len >= 2);
174         LZ_ASSERT(mf->params.max_match_len >= mf->params.min_match_len);
175
176         return mf;
177 }
178
179 /*
180  * Load a window into the match-finder.
181  *
182  * @mf
183  *      The match-finder into which to load the window.
184  * @window
185  *      Pointer to the window to load.  This memory must remain available,
186  *      unmodified, while the match-finder is being used.
187  * @size
188  *      The size of the window, in bytes.  This can't be larger than the
189  *      @max_window_size parameter.  In addition, this can't be 0.
190  *
191  * Note: this interface does not support sliding windows!
192  */
193 void
194 lz_mf_load_window(struct lz_mf *mf, const u8 *window, u32 size)
195 {
196         /* Can't be an empty window, and can't be larger than the maximum window
197          * size with which the match-finder was allocated.  */
198         LZ_ASSERT(size > 0);
199         LZ_ASSERT(size <= mf->params.max_window_size);
200
201         /* Save the window and initialize the current position.  */
202         mf->cur_window = window;
203         mf->cur_window_size = size;
204         mf->cur_window_pos = 0;
205
206         /* Call into the algorithm-specific window load code.  */
207         mf->ops.load_window(mf, window, size);
208 }
209
210 /*
211  * Retrieve a list of matches at the next position in the window.
212  *
213  * @mf
214  *      The match-finder into which a window has been loaded using
215  *      lz_mf_load_window().
216  * @matches
217  *      The array into which the matches will be returned.  The returned match
218  *      count will not exceed the minimum of @max_search_depth and (@len_limit -
219  *      @min_match_len + 1), where @len_limit is itself defined as
220  *      min(@max_match_len, @nice_match_len).
221  *
222  * The return value is the number of matches that were found and stored in the
223  * 'matches' array.  The matches will be ordered by strictly increasing length
224  * and strictly increasing offset.  No match shall have length less than
225  * @min_match_len, and no match shall have length greater than @max_match_len.
226  * The return value may be 0, which indicates that no matches were found.
227  *
228  * On completion, the match-finder is advanced to the next position in the
229  * window.
230  *
231  * Note: in-non-debug mode, the inline definition of this gets used instead.
232  * They are the same, except that the non-inline version below validates the
233  * results to help debug match-finding algorithms.
234  */
235 #ifdef ENABLE_LZ_DEBUG
236 u32
237 lz_mf_get_matches(struct lz_mf *mf, struct lz_match *matches)
238 {
239         LZ_ASSERT(mf->cur_window_pos < mf->cur_window_size);
240
241         const u32 orig_pos = mf->cur_window_pos;
242         const u32 len_limit = min(mf->params.max_match_len,
243                                   lz_mf_get_bytes_remaining(mf));
244         const u8 * const strptr = lz_mf_get_window_ptr(mf);
245
246         const u32 num_matches = mf->ops.get_matches(mf, matches);
247
248         LZ_ASSERT(mf->cur_window_pos == orig_pos + 1);
249
250 #if 0
251         fprintf(stderr, "Pos %"PRIu32"/%"PRIu32": %"PRIu32" matches\n",
252                 orig_pos, mf->cur_window_size, num_matches);
253         for (u32 i = 0; i < num_matches; i++) {
254                 fprintf(stderr, "\tLen %"PRIu32" Offset %"PRIu32"\n",
255                         matches[i].len, matches[i].offset);
256         }
257 #endif
258
259         /* Validate the matches.  */
260         for (u32 i = 0; i < num_matches; i++) {
261                 const u32 len = matches[i].len;
262                 const u32 offset = matches[i].offset;
263                 const u8 *matchptr;
264
265                 /* Length valid?  */
266                 LZ_ASSERT(len >= mf->params.min_match_len);
267                 LZ_ASSERT(len <= len_limit);
268
269                 /* Offset valid?  */
270                 LZ_ASSERT(offset >= 1);
271                 LZ_ASSERT(offset <= orig_pos);
272
273                 /* Lengths and offsets strictly increasing?  */
274                 if (i > 0) {
275                         LZ_ASSERT(len > matches[i - 1].len);
276                         LZ_ASSERT(offset > matches[i - 1].offset);
277                 }
278
279                 /* Actually a match?  */
280                 matchptr = strptr - offset;
281                 LZ_ASSERT(!memcmp(strptr, matchptr, len));
282
283                 /* Match can't be extended further?  */
284                 LZ_ASSERT(len == len_limit || strptr[len] != matchptr[len]);
285         }
286
287         return num_matches;
288 }
289 #endif /* ENABLE_LZ_DEBUG */
290
291 /*
292  * Skip 'n' positions in the match-finder.  This is a faster alternative to
293  * calling lz_mf_get_matches() at each position to advance the match-finder.
294  *
295  * 'n' must be greater than 0.
296  *
297  * Note: in-non-debug mode, the inline definition of this gets used instead.
298  * They are the same, except the non-inline version below does extra checks.
299  */
300 #ifdef ENABLE_LZ_DEBUG
301 void
302 lz_mf_skip_positions(struct lz_mf *mf, const u32 n)
303 {
304         LZ_ASSERT(n > 0);
305         LZ_ASSERT(n <= lz_mf_get_bytes_remaining(mf));
306
307         const u32 orig_pos = mf->cur_window_pos;
308
309         mf->ops.skip_positions(mf, n);
310
311         LZ_ASSERT(mf->cur_window_pos == orig_pos + n);
312 }
313 #endif
314
315 /*
316  * Free the match-finder.
317  *
318  * This frees all memory that was allocated by the call to lz_mf_alloc().
319  */
320 void
321 lz_mf_free(struct lz_mf *mf)
322 {
323         if (mf) {
324                 mf->ops.destroy(mf);
325         #ifdef ENABLE_LZ_DEBUG
326                 memset(mf, 0, mf->ops.struct_size);
327         #endif
328                 FREE(mf);
329         }
330 }