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