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