]> wimlib.net Git - wimlib/blob - include/wimlib/bt_matchfinder.h
Use more comprehensive public domain dedications
[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-2015 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 inline 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 inline void
120 TEMPLATED(bt_matchfinder_init)(struct TEMPLATED(bt_matchfinder) *mf)
121 {
122         memset(mf, 0, sizeof(*mf));
123 }
124
125 static inline 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 inline 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 inline 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,
248                                         (record_matches ? max_len : nice_len));
249                         if (!record_matches || len > best_len) {
250                                 if (record_matches) {
251                                         best_len = len;
252                                         lz_matchptr->length = len;
253                                         lz_matchptr->offset = in_next - matchptr;
254                                         lz_matchptr++;
255                                 }
256                                 if (len >= nice_len) {
257                                         *pending_lt_ptr = *TEMPLATED(bt_left_child)(mf, cur_node);
258                                         *pending_gt_ptr = *TEMPLATED(bt_right_child)(mf, cur_node);
259                                         *best_len_ret = best_len;
260                                         return lz_matchptr;
261                                 }
262                         }
263                 }
264
265                 if (matchptr[len] < in_next[len]) {
266                         *pending_lt_ptr = cur_node;
267                         pending_lt_ptr = TEMPLATED(bt_right_child)(mf, cur_node);
268                         cur_node = *pending_lt_ptr;
269                         best_lt_len = len;
270                         if (best_gt_len < len)
271                                 len = best_gt_len;
272                 } else {
273                         *pending_gt_ptr = cur_node;
274                         pending_gt_ptr = TEMPLATED(bt_left_child)(mf, cur_node);
275                         cur_node = *pending_gt_ptr;
276                         best_gt_len = len;
277                         if (best_lt_len < len)
278                                 len = best_lt_len;
279                 }
280
281                 if (!cur_node || !--depth_remaining) {
282                         *pending_lt_ptr = 0;
283                         *pending_gt_ptr = 0;
284                         *best_len_ret = best_len;
285                         return lz_matchptr;
286                 }
287         }
288 }
289
290 /*
291  * Retrieve a list of matches with the current position.
292  *
293  * @mf
294  *      The matchfinder structure.
295  * @in_begin
296  *      Pointer to the beginning of the input buffer.
297  * @cur_pos
298  *      The current position in the input buffer (the position of the sequence
299  *      being matched against).
300  * @max_len
301  *      The maximum permissible match length at this position.  Must be >=
302  *      BT_MATCHFINDER_REQUIRED_NBYTES.
303  * @nice_len
304  *      Stop searching if a match of at least this length is found.
305  *      Must be <= @max_len.
306  * @max_search_depth
307  *      Limit on the number of potential matches to consider.  Must be >= 1.
308  * @next_hashes
309  *      The precomputed hash codes for the sequence beginning at @in_next.
310  *      These will be used and then updated with the precomputed hashcodes for
311  *      the sequence beginning at @in_next + 1.
312  * @best_len_ret
313  *      If a match of length >= 4 was found, then the length of the longest such
314  *      match is written here; otherwise 3 is written here.  (Note: this is
315  *      redundant with the 'struct lz_match' array, but this is easier for the
316  *      compiler to optimize when inlined and the caller immediately does a
317  *      check against 'best_len'.)
318  * @lz_matchptr
319  *      An array in which this function will record the matches.  The recorded
320  *      matches will be sorted by strictly increasing length and (non-strictly)
321  *      increasing offset.  The maximum number of matches that may be found is
322  *      'nice_len - 1', or one less if length 2 matches are disabled.
323  *
324  * The return value is a pointer to the next available slot in the @lz_matchptr
325  * array.  (If no matches were found, this will be the same as @lz_matchptr.)
326  */
327 static inline struct lz_match *
328 TEMPLATED(bt_matchfinder_get_matches)(struct TEMPLATED(bt_matchfinder) *mf,
329                                       const u8 *in_begin,
330                                       ptrdiff_t cur_pos,
331                                       u32 max_len,
332                                       u32 nice_len,
333                                       u32 max_search_depth,
334                                       u32 next_hashes[static 2],
335                                       u32 *best_len_ret,
336                                       struct lz_match *lz_matchptr)
337 {
338         return TEMPLATED(bt_matchfinder_advance_one_byte)(mf,
339                                                           in_begin,
340                                                           cur_pos,
341                                                           max_len,
342                                                           nice_len,
343                                                           max_search_depth,
344                                                           next_hashes,
345                                                           best_len_ret,
346                                                           lz_matchptr,
347                                                           true);
348 }
349
350 /*
351  * Advance the matchfinder, but don't record any matches.
352  *
353  * This is very similar to bt_matchfinder_get_matches() because both functions
354  * must do hashing and tree re-rooting.
355  */
356 static inline void
357 TEMPLATED(bt_matchfinder_skip_position)(struct TEMPLATED(bt_matchfinder) *mf,
358                                         const u8 *in_begin,
359                                         ptrdiff_t cur_pos,
360                                         u32 max_len,
361                                         u32 nice_len,
362                                         u32 max_search_depth,
363                                         u32 next_hashes[static 2])
364 {
365         u32 best_len;
366         TEMPLATED(bt_matchfinder_advance_one_byte)(mf,
367                                                    in_begin,
368                                                    cur_pos,
369                                                    max_len,
370                                                    nice_len,
371                                                    max_search_depth,
372                                                    next_hashes,
373                                                    &best_len,
374                                                    NULL,
375                                                    false);
376 }