]> wimlib.net Git - wimlib/blob - include/wimlib/bt_matchfinder.h
mount_image.c: add fallback definitions of RENAME_* constants
[wimlib] / include / wimlib / bt_matchfinder.h
1 /*
2  * bt_matchfinder.h - Lempel-Ziv matchfinding with a hash table of binary trees
3  *
4  * Copyright 2022 Eric Biggers
5  *
6  * Permission is hereby granted, free of charge, to any person
7  * obtaining a copy of this software and associated documentation
8  * files (the "Software"), to deal in the Software without
9  * restriction, including without limitation the rights to use,
10  * copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following
13  * conditions:
14  *
15  * The above copyright notice and this permission notice shall be
16  * included in all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25  * OTHER DEALINGS IN THE SOFTWARE.
26  *
27  * ----------------------------------------------------------------------------
28  *
29  * This is a Binary Trees (bt) based matchfinder.
30  *
31  * The main data structure is a hash table where each hash bucket contains a
32  * binary tree of sequences whose first 4 bytes share the same hash code.  Each
33  * sequence is identified by its starting position in the input buffer.  Each
34  * binary tree is always sorted such that each left child represents a sequence
35  * lexicographically lesser than its parent and each right child represents a
36  * sequence lexicographically greater than its parent.
37  *
38  * The algorithm processes the input buffer sequentially.  At each byte
39  * position, the hash code of the first 4 bytes of the sequence beginning at
40  * that position (the sequence being matched against) is computed.  This
41  * identifies the hash bucket to use for that position.  Then, a new binary tree
42  * node is created to represent the current sequence.  Then, in a single tree
43  * traversal, the hash bucket's binary tree is searched for matches and is
44  * re-rooted at the new node.
45  *
46  * Compared to the simpler algorithm that uses linked lists instead of binary
47  * trees (see hc_matchfinder.h), the binary tree version gains more information
48  * at each node visitation.  Ideally, the binary tree version will examine only
49  * 'log(n)' nodes to find the same matches that the linked list version will
50  * find by examining 'n' nodes.  In addition, the binary tree version can
51  * examine fewer bytes at each node by taking advantage of the common prefixes
52  * that result from the sort order, whereas the linked list version may have to
53  * examine up to the full length of the match at each node.
54  *
55  * However, it is not always best to use the binary tree version.  It requires
56  * nearly twice as much memory as the linked list version, and it takes time to
57  * keep the binary trees sorted, even at positions where the compressor does not
58  * need matches.  Generally, when doing fast compression on small buffers,
59  * binary trees are the wrong approach.  They are best suited for thorough
60  * compression and/or large buffers.
61  *
62  * ----------------------------------------------------------------------------
63  */
64
65
66 #include <string.h>
67
68 #include "wimlib/matchfinder_common.h"
69
70 #define BT_MATCHFINDER_HASH3_ORDER 15
71 #define BT_MATCHFINDER_HASH3_WAYS  2
72 #define BT_MATCHFINDER_HASH4_ORDER 16
73
74 /* TEMPLATED functions and structures have MF_SUFFIX appended to their name.  */
75 #undef TEMPLATED
76 #define TEMPLATED(name)         CONCAT(name, MF_SUFFIX)
77
78 #ifndef _WIMLIB_BT_MATCHFINDER_H
79 #define _WIMLIB_BT_MATCHFINDER_H
80
81 /* Non-templated definitions  */
82
83 /* Representation of a match found by the bt_matchfinder  */
84 struct lz_match {
85
86         /* The number of bytes matched.  */
87         u32 length;
88
89         /* The offset back from the current position that was matched.  */
90         u32 offset;
91 };
92
93 #endif /* _WIMLIB_BT_MATCHFINDER_H */
94
95 struct TEMPLATED(bt_matchfinder) {
96
97         /* The hash table for finding length 2 matches, if enabled  */
98 #ifdef BT_MATCHFINDER_HASH2_ORDER
99         mf_pos_t hash2_tab[1UL << BT_MATCHFINDER_HASH2_ORDER];
100 #endif
101
102         /* The hash table for finding length 3 matches  */
103         mf_pos_t hash3_tab[1UL << BT_MATCHFINDER_HASH3_ORDER][BT_MATCHFINDER_HASH3_WAYS];
104
105         /* The hash table which contains the roots of the binary trees for
106          * finding length 4+ matches  */
107         mf_pos_t hash4_tab[1UL << BT_MATCHFINDER_HASH4_ORDER];
108
109         /* The child node references for the binary trees.  The left and right
110          * children of the node for the sequence with position 'pos' are
111          * 'child_tab[pos * 2]' and 'child_tab[pos * 2 + 1]', respectively.  */
112         mf_pos_t child_tab[];
113 };
114
115 /* Return the number of bytes that must be allocated for a 'bt_matchfinder' that
116  * can work with buffers up to the specified size.  */
117 static forceinline size_t
118 TEMPLATED(bt_matchfinder_size)(size_t max_bufsize)
119 {
120         return sizeof(struct TEMPLATED(bt_matchfinder)) +
121                 (2 * max_bufsize * sizeof(mf_pos_t));
122 }
123
124 /* Prepare the matchfinder for a new input buffer.  */
125 static forceinline void
126 TEMPLATED(bt_matchfinder_init)(struct TEMPLATED(bt_matchfinder) *mf)
127 {
128         memset(mf, 0, sizeof(*mf));
129 }
130
131 static forceinline mf_pos_t *
132 TEMPLATED(bt_left_child)(struct TEMPLATED(bt_matchfinder) *mf, u32 node)
133 {
134         return &mf->child_tab[(node << 1) + 0];
135 }
136
137 static forceinline mf_pos_t *
138 TEMPLATED(bt_right_child)(struct TEMPLATED(bt_matchfinder) *mf, u32 node)
139 {
140         return &mf->child_tab[(node << 1) + 1];
141 }
142
143 /* The minimum permissible value of 'max_len' for bt_matchfinder_get_matches()
144  * and bt_matchfinder_skip_byte().  There must be sufficiently many bytes
145  * remaining to load a 32-bit integer from the *next* position.  */
146 #define BT_MATCHFINDER_REQUIRED_NBYTES  5
147
148 /* Advance the binary tree matchfinder by one byte, optionally recording
149  * matches.  @record_matches should be a compile-time constant.  */
150 static forceinline struct lz_match *
151 TEMPLATED(bt_matchfinder_advance_one_byte)(struct TEMPLATED(bt_matchfinder) * const mf,
152                                            const u8 * const in_begin,
153                                            const ptrdiff_t cur_pos,
154                                            const u32 max_len,
155                                            const u32 nice_len,
156                                            const u32 max_search_depth,
157                                            u32 * const next_hashes,
158                                            u32 * const best_len_ret,
159                                            struct lz_match *lz_matchptr,
160                                            const bool record_matches)
161 {
162         const u8 *in_next = in_begin + cur_pos;
163         u32 depth_remaining = max_search_depth;
164         u32 next_hashseq;
165         u32 hash3;
166         u32 hash4;
167 #ifdef BT_MATCHFINDER_HASH2_ORDER
168         u16 seq2;
169         u32 hash2;
170 #endif
171         STATIC_ASSERT(BT_MATCHFINDER_HASH3_WAYS >= 1 &&
172                       BT_MATCHFINDER_HASH3_WAYS <= 2);
173         u32 cur_node;
174 #if BT_MATCHFINDER_HASH3_WAYS >= 2
175         u32 cur_node_2;
176 #endif
177         const u8 *matchptr;
178         mf_pos_t *pending_lt_ptr, *pending_gt_ptr;
179         u32 best_lt_len, best_gt_len;
180         u32 len;
181         u32 best_len = 3;
182
183         next_hashseq = get_unaligned_le32(in_next + 1);
184
185         hash3 = next_hashes[0];
186         hash4 = next_hashes[1];
187
188         next_hashes[0] = lz_hash(next_hashseq & 0xFFFFFF, BT_MATCHFINDER_HASH3_ORDER);
189         next_hashes[1] = lz_hash(next_hashseq, BT_MATCHFINDER_HASH4_ORDER);
190         prefetchw(&mf->hash3_tab[next_hashes[0]]);
191         prefetchw(&mf->hash4_tab[next_hashes[1]]);
192
193 #ifdef BT_MATCHFINDER_HASH2_ORDER
194         seq2 = load_u16_unaligned(in_next);
195         hash2 = lz_hash(seq2, BT_MATCHFINDER_HASH2_ORDER);
196         cur_node = mf->hash2_tab[hash2];
197         mf->hash2_tab[hash2] = cur_pos;
198         if (record_matches &&
199             seq2 == load_u16_unaligned(&in_begin[cur_node]) &&
200             likely(in_next != in_begin))
201         {
202                 lz_matchptr->length = 2;
203                 lz_matchptr->offset = in_next - &in_begin[cur_node];
204                 lz_matchptr++;
205         }
206 #endif
207
208         cur_node = mf->hash3_tab[hash3][0];
209         mf->hash3_tab[hash3][0] = cur_pos;
210 #if BT_MATCHFINDER_HASH3_WAYS >= 2
211         cur_node_2 = mf->hash3_tab[hash3][1];
212         mf->hash3_tab[hash3][1] = cur_node;
213 #endif
214         if (record_matches && likely(in_next != in_begin)) {
215                 u32 seq3 = load_u24_unaligned(in_next);
216                 if (seq3 == load_u24_unaligned(&in_begin[cur_node])) {
217                         lz_matchptr->length = 3;
218                         lz_matchptr->offset = in_next - &in_begin[cur_node];
219                         lz_matchptr++;
220                 }
221         #if BT_MATCHFINDER_HASH3_WAYS >= 2
222                 else if (seq3 == load_u24_unaligned(&in_begin[cur_node_2])) {
223                         lz_matchptr->length = 3;
224                         lz_matchptr->offset = in_next - &in_begin[cur_node_2];
225                         lz_matchptr++;
226                 }
227         #endif
228         }
229
230         cur_node = mf->hash4_tab[hash4];
231         mf->hash4_tab[hash4] = cur_pos;
232
233         pending_lt_ptr = TEMPLATED(bt_left_child)(mf, cur_pos);
234         pending_gt_ptr = TEMPLATED(bt_right_child)(mf, cur_pos);
235
236         if (!cur_node) {
237                 *pending_lt_ptr = 0;
238                 *pending_gt_ptr = 0;
239                 *best_len_ret = best_len;
240                 return lz_matchptr;
241         }
242
243         best_lt_len = 0;
244         best_gt_len = 0;
245         len = 0;
246
247         for (;;) {
248                 matchptr = &in_begin[cur_node];
249
250                 if (matchptr[len] == in_next[len]) {
251                         len = lz_extend(in_next, matchptr, len + 1, max_len);
252                         if (!record_matches || len > best_len) {
253                                 if (record_matches) {
254                                         best_len = len;
255                                         lz_matchptr->length = len;
256                                         lz_matchptr->offset = in_next - matchptr;
257                                         lz_matchptr++;
258                                 }
259                                 if (len >= nice_len) {
260                                         *pending_lt_ptr = *TEMPLATED(bt_left_child)(mf, cur_node);
261                                         *pending_gt_ptr = *TEMPLATED(bt_right_child)(mf, cur_node);
262                                         *best_len_ret = best_len;
263                                         return lz_matchptr;
264                                 }
265                         }
266                 }
267
268                 if (matchptr[len] < in_next[len]) {
269                         *pending_lt_ptr = cur_node;
270                         pending_lt_ptr = TEMPLATED(bt_right_child)(mf, cur_node);
271                         cur_node = *pending_lt_ptr;
272                         best_lt_len = len;
273                         if (best_gt_len < len)
274                                 len = best_gt_len;
275                 } else {
276                         *pending_gt_ptr = cur_node;
277                         pending_gt_ptr = TEMPLATED(bt_left_child)(mf, cur_node);
278                         cur_node = *pending_gt_ptr;
279                         best_gt_len = len;
280                         if (best_lt_len < len)
281                                 len = best_lt_len;
282                 }
283
284                 if (!cur_node || !--depth_remaining) {
285                         *pending_lt_ptr = 0;
286                         *pending_gt_ptr = 0;
287                         *best_len_ret = best_len;
288                         return lz_matchptr;
289                 }
290         }
291 }
292
293 /*
294  * Retrieve a list of matches with the current position.
295  *
296  * @mf
297  *      The matchfinder structure.
298  * @in_begin
299  *      Pointer to the beginning of the input buffer.
300  * @cur_pos
301  *      The current position in the input buffer relative to @in_begin (the
302  *      position of the sequence being matched against).
303  * @max_len
304  *      The maximum permissible match length at this position.  Must be >=
305  *      BT_MATCHFINDER_REQUIRED_NBYTES.
306  * @nice_len
307  *      Stop searching if a match of at least this length is found.
308  *      Must be <= @max_len.
309  * @max_search_depth
310  *      Limit on the number of potential matches to consider.  Must be >= 1.
311  * @next_hashes
312  *      The precomputed hash codes for the sequence beginning at @in_next.
313  *      These will be used and then updated with the precomputed hashcodes for
314  *      the sequence beginning at @in_next + 1.
315  * @best_len_ret
316  *      If a match of length >= 4 was found, then the length of the longest such
317  *      match is written here; otherwise 3 is written here.  (Note: this is
318  *      redundant with the 'struct lz_match' array, but this is easier for the
319  *      compiler to optimize when inlined and the caller immediately does a
320  *      check against 'best_len'.)
321  * @lz_matchptr
322  *      An array in which this function will record the matches.  The recorded
323  *      matches will be sorted by strictly increasing length and (non-strictly)
324  *      increasing offset.  The maximum number of matches that may be found is
325  *      'nice_len - 1', or one less if length 2 matches are disabled.
326  *
327  * The return value is a pointer to the next available slot in the @lz_matchptr
328  * array.  (If no matches were found, this will be the same as @lz_matchptr.)
329  */
330 static forceinline struct lz_match *
331 TEMPLATED(bt_matchfinder_get_matches)(struct TEMPLATED(bt_matchfinder) *mf,
332                                       const u8 *in_begin,
333                                       ptrdiff_t cur_pos,
334                                       u32 max_len,
335                                       u32 nice_len,
336                                       u32 max_search_depth,
337                                       u32 next_hashes[2],
338                                       u32 *best_len_ret,
339                                       struct lz_match *lz_matchptr)
340 {
341         return TEMPLATED(bt_matchfinder_advance_one_byte)(mf,
342                                                           in_begin,
343                                                           cur_pos,
344                                                           max_len,
345                                                           nice_len,
346                                                           max_search_depth,
347                                                           next_hashes,
348                                                           best_len_ret,
349                                                           lz_matchptr,
350                                                           true);
351 }
352
353 /*
354  * Advance the matchfinder, but don't record any matches.
355  *
356  * This is very similar to bt_matchfinder_get_matches() because both functions
357  * must do hashing and tree re-rooting.
358  */
359 static forceinline void
360 TEMPLATED(bt_matchfinder_skip_byte)(struct TEMPLATED(bt_matchfinder) *mf,
361                                     const u8 *in_begin,
362                                     ptrdiff_t cur_pos,
363                                     u32 nice_len,
364                                     u32 max_search_depth,
365                                     u32 next_hashes[2])
366 {
367         u32 best_len;
368         TEMPLATED(bt_matchfinder_advance_one_byte)(mf,
369                                                    in_begin,
370                                                    cur_pos,
371                                                    nice_len,
372                                                    nice_len,
373                                                    max_search_depth,
374                                                    next_hashes,
375                                                    &best_len,
376                                                    NULL,
377                                                    false);
378 }