]> wimlib.net Git - wimlib/blob - include/wimlib/bt_matchfinder.h
1a94497845cd0a4d34380c8d7f69ba812f7e08a2
[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 3 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 3 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 16
55
56 /* TEMPLATED functions and structures have MF_SUFFIX appended to their name.  */
57 #undef TEMPLATED
58 #define TEMPLATED(name)         CONCAT(name, MF_SUFFIX)
59
60 #ifndef _WIMLIB_BT_MATCHFINDER_H
61 #define _WIMLIB_BT_MATCHFINDER_H
62
63 /* Non-templated definitions  */
64
65 /* Representation of a match found by the bt_matchfinder  */
66 struct lz_match {
67
68         /* The number of bytes matched.  */
69         u32 length;
70
71         /* The offset back from the current position that was matched.  */
72         u32 offset;
73 };
74
75 #endif /* _WIMLIB_BT_MATCHFINDER_H */
76
77 struct TEMPLATED(bt_matchfinder) {
78
79         /* The hash table for finding length 2 matches, if enabled  */
80 #ifdef BT_MATCHFINDER_HASH2_ORDER
81         mf_pos_t hash2_tab[1UL << BT_MATCHFINDER_HASH2_ORDER];
82 #endif
83
84         /* The hash table which contains the roots of the binary trees for
85          * finding length 3 matches  */
86         mf_pos_t hash3_tab[1UL << BT_MATCHFINDER_HASH3_ORDER];
87
88         /* The child node references for the binary trees.  The left and right
89          * children of the node for the sequence with position 'pos' are
90          * 'child_tab[pos * 2]' and 'child_tab[pos * 2 + 1]', respectively.  */
91         mf_pos_t child_tab[];
92 };
93
94 /* Return the number of bytes that must be allocated for a 'bt_matchfinder' that
95  * can work with buffers up to the specified size.  */
96 static inline size_t
97 TEMPLATED(bt_matchfinder_size)(size_t max_bufsize)
98 {
99         return sizeof(struct TEMPLATED(bt_matchfinder)) +
100                 (2 * max_bufsize * sizeof(mf_pos_t));
101 }
102
103 /* Prepare the matchfinder for a new input buffer.  */
104 static inline void
105 TEMPLATED(bt_matchfinder_init)(struct TEMPLATED(bt_matchfinder) *mf)
106 {
107         memset(mf, 0, sizeof(*mf));
108 }
109
110 static inline mf_pos_t *
111 TEMPLATED(bt_left_child)(struct TEMPLATED(bt_matchfinder) *mf, u32 node)
112 {
113         return &mf->child_tab[(node << 1) + 0];
114 }
115
116 static inline mf_pos_t *
117 TEMPLATED(bt_right_child)(struct TEMPLATED(bt_matchfinder) *mf, u32 node)
118 {
119         return &mf->child_tab[(node << 1) + 1];
120 }
121
122 /* Advance the binary tree matchfinder by one byte, optionally recording
123  * matches.  @record_matches should be a compile-time constant.  */
124 static inline struct lz_match *
125 TEMPLATED(bt_matchfinder_advance_one_byte)(struct TEMPLATED(bt_matchfinder) * const restrict mf,
126                                            const u8 * const restrict in_begin,
127                                            const ptrdiff_t cur_pos,
128                                            const u32 max_len,
129                                            const u32 nice_len,
130                                            const u32 max_search_depth,
131                                            u32 * const restrict next_hash,
132                                            u32 * const restrict best_len_ret,
133                                            struct lz_match * restrict lz_matchptr,
134                                            const bool record_matches)
135 {
136         const u8 *in_next = in_begin + cur_pos;
137         u32 depth_remaining = max_search_depth;
138 #ifdef BT_MATCHFINDER_HASH2_ORDER
139         u16 seq2;
140         u32 hash2;
141 #endif
142         u32 hash3;
143         u32 cur_node;
144         const u8 *matchptr;
145         mf_pos_t *pending_lt_ptr, *pending_gt_ptr;
146         u32 best_lt_len, best_gt_len;
147         u32 len;
148         u32 best_len = 2;
149
150         hash3 = *next_hash;
151         *next_hash = lz_hash(load_u24_unaligned(in_next + 1), BT_MATCHFINDER_HASH3_ORDER);
152         prefetchw(&mf->hash3_tab[*next_hash]);
153
154 #ifdef BT_MATCHFINDER_HASH2_ORDER
155         seq2 = load_u16_unaligned(in_next);
156         hash2 = lz_hash(seq2, BT_MATCHFINDER_HASH2_ORDER);
157         cur_node = mf->hash2_tab[hash2];
158         mf->hash2_tab[hash2] = cur_pos;
159         if (record_matches &&
160             seq2 == load_u16_unaligned(&in_begin[cur_node]) &&
161             likely(in_next != in_begin))
162         {
163                 lz_matchptr->length = 2;
164                 lz_matchptr->offset = in_next - &in_begin[cur_node];
165                 lz_matchptr++;
166         }
167 #endif
168
169         cur_node = mf->hash3_tab[hash3];
170         mf->hash3_tab[hash3] = cur_pos;
171
172         pending_lt_ptr = TEMPLATED(bt_left_child)(mf, cur_pos);
173         pending_gt_ptr = TEMPLATED(bt_right_child)(mf, cur_pos);
174
175         if (!cur_node) {
176                 *pending_lt_ptr = 0;
177                 *pending_gt_ptr = 0;
178                 *best_len_ret = best_len;
179                 return lz_matchptr;
180         }
181
182         best_lt_len = 0;
183         best_gt_len = 0;
184         len = 0;
185
186         for (;;) {
187                 matchptr = &in_begin[cur_node];
188
189                 if (matchptr[len] == in_next[len]) {
190                         len = lz_extend(in_next, matchptr, len + 1,
191                                         (record_matches ? max_len : nice_len));
192                         if (!record_matches || len > best_len) {
193                                 if (record_matches) {
194                                         best_len = len;
195                                         lz_matchptr->length = len;
196                                         lz_matchptr->offset = in_next - matchptr;
197                                         lz_matchptr++;
198                                 }
199                                 if (len >= nice_len) {
200                                         *pending_lt_ptr = *TEMPLATED(bt_left_child)(mf, cur_node);
201                                         *pending_gt_ptr = *TEMPLATED(bt_right_child)(mf, cur_node);
202                                         *best_len_ret = best_len;
203                                         return lz_matchptr;
204                                 }
205                         }
206                 }
207
208                 if (matchptr[len] < in_next[len]) {
209                         *pending_lt_ptr = cur_node;
210                         pending_lt_ptr = TEMPLATED(bt_right_child)(mf, cur_node);
211                         cur_node = *pending_lt_ptr;
212                         best_lt_len = len;
213                         if (best_gt_len < len)
214                                 len = best_gt_len;
215                 } else {
216                         *pending_gt_ptr = cur_node;
217                         pending_gt_ptr = TEMPLATED(bt_left_child)(mf, cur_node);
218                         cur_node = *pending_gt_ptr;
219                         best_gt_len = len;
220                         if (best_lt_len < len)
221                                 len = best_lt_len;
222                 }
223
224                 if (!cur_node || !--depth_remaining) {
225                         *pending_lt_ptr = 0;
226                         *pending_gt_ptr = 0;
227                         *best_len_ret = best_len;
228                         return lz_matchptr;
229                 }
230         }
231 }
232
233 /*
234  * Retrieve a list of matches with the current position.
235  *
236  * @mf
237  *      The matchfinder structure.
238  * @in_begin
239  *      Pointer to the beginning of the input buffer.
240  * @cur_pos
241  *      The current position in the input buffer (the position of the sequence
242  *      being matched against).
243  * @max_len
244  *      The maximum permissible match length at this position.  Must be >= 5.
245  * @nice_len
246  *      Stop searching if a match of at least this length is found.
247  *      Must be <= @max_len.
248  * @max_search_depth
249  *      Limit on the number of potential matches to consider.  Must be >= 1.
250  * @next_hash
251  *      Pointer to the hash code for the current sequence, which was computed
252  *      one position in advance so that the binary tree root could be
253  *      prefetched.  This is an input/output parameter.
254  * @best_len_ret
255  *      If a match of length >= 3 was found, then the length of the longest such
256  *      match is written here; otherwise 2 is written here.  (Note: this is
257  *      redundant with the 'struct lz_match' array, but this is easier for the
258  *      compiler to optimize when inlined and the caller immediately does a
259  *      check against 'best_len'.)
260  * @lz_matchptr
261  *      An array in which this function will record the matches.  The recorded
262  *      matches will be sorted by strictly increasing length and increasing
263  *      offset.  The maximum number of matches that may be found is
264  *      'min(nice_len, max_len) - 2 + 1', or one less if length 2 matches are
265  *      disabled.
266  *
267  * The return value is a pointer to the next available slot in the @lz_matchptr
268  * array.  (If no matches were found, this will be the same as @lz_matchptr.)
269  */
270 static inline struct lz_match *
271 TEMPLATED(bt_matchfinder_get_matches)(struct TEMPLATED(bt_matchfinder) *mf,
272                                       const u8 *in_begin,
273                                       ptrdiff_t cur_pos,
274                                       u32 max_len,
275                                       u32 nice_len,
276                                       u32 max_search_depth,
277                                       u32 *next_hash,
278                                       u32 *best_len_ret,
279                                       struct lz_match *lz_matchptr)
280 {
281         return TEMPLATED(bt_matchfinder_advance_one_byte)(mf,
282                                                           in_begin,
283                                                           cur_pos,
284                                                           max_len,
285                                                           nice_len,
286                                                           max_search_depth,
287                                                           next_hash,
288                                                           best_len_ret,
289                                                           lz_matchptr,
290                                                           true);
291 }
292
293 /*
294  * Advance the matchfinder, but don't record any matches.
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.
302  * @max_len
303  *      The maximum permissible match length at this position.  Must be >= 5.
304  * @nice_len
305  *      Stop searching if a match of at least this length is found.
306  * @max_search_depth
307  *      Limit on the number of potential matches to consider.
308  * @next_hash
309  *      Pointer to the hash code for the current sequence, which was computed
310  *      one position in advance so that the binary tree root could be
311  *      prefetched.  This is an input/output parameter.
312  *
313  * Note: this is very similar to bt_matchfinder_get_matches() because both
314  * functions must do hashing and tree re-rooting.  This version just doesn't
315  * actually record any matches.
316  */
317 static inline void
318 TEMPLATED(bt_matchfinder_skip_position)(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_hash)
325 {
326         u32 best_len;
327         TEMPLATED(bt_matchfinder_advance_one_byte)(mf,
328                                                    in_begin,
329                                                    cur_pos,
330                                                    max_len,
331                                                    nice_len,
332                                                    max_search_depth,
333                                                    next_hash,
334                                                    &best_len,
335                                                    NULL,
336                                                    false);
337 }