]> wimlib.net Git - wimlib/blob - include/wimlib/bt_matchfinder.h
Rename 'pos_t' to 'mf_pos_t'
[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         if (unlikely(max_len < LZ_HASH3_REQUIRED_NBYTES + 1)) {
151                 *best_len_ret = best_len;
152                 return lz_matchptr;
153         }
154
155         hash3 = *next_hash;
156         *next_hash = lz_hash(load_u24_unaligned(in_next + 1), BT_MATCHFINDER_HASH3_ORDER);
157         prefetchw(&mf->hash3_tab[*next_hash]);
158
159 #ifdef BT_MATCHFINDER_HASH2_ORDER
160         seq2 = load_u16_unaligned(in_next);
161         hash2 = lz_hash(seq2, BT_MATCHFINDER_HASH2_ORDER);
162         cur_node = mf->hash2_tab[hash2];
163         mf->hash2_tab[hash2] = cur_pos;
164         if (record_matches &&
165             seq2 == load_u16_unaligned(&in_begin[cur_node]) &&
166             likely(in_next != in_begin))
167         {
168                 lz_matchptr->length = 2;
169                 lz_matchptr->offset = in_next - &in_begin[cur_node];
170                 lz_matchptr++;
171         }
172 #endif
173
174         cur_node = mf->hash3_tab[hash3];
175         mf->hash3_tab[hash3] = cur_pos;
176
177         pending_lt_ptr = TEMPLATED(bt_left_child)(mf, cur_pos);
178         pending_gt_ptr = TEMPLATED(bt_right_child)(mf, cur_pos);
179
180         if (!cur_node) {
181                 *pending_lt_ptr = 0;
182                 *pending_gt_ptr = 0;
183                 *best_len_ret = best_len;
184                 return lz_matchptr;
185         }
186
187         best_lt_len = 0;
188         best_gt_len = 0;
189         len = 0;
190
191         for (;;) {
192                 matchptr = &in_begin[cur_node];
193
194                 if (matchptr[len] == in_next[len]) {
195                         len = lz_extend(in_next, matchptr, len + 1,
196                                         (record_matches ? max_len : nice_len));
197                         if (!record_matches || len > best_len) {
198                                 if (record_matches) {
199                                         best_len = len;
200                                         lz_matchptr->length = len;
201                                         lz_matchptr->offset = in_next - matchptr;
202                                         lz_matchptr++;
203                                 }
204                                 if (len >= nice_len) {
205                                         *pending_lt_ptr = *TEMPLATED(bt_left_child)(mf, cur_node);
206                                         *pending_gt_ptr = *TEMPLATED(bt_right_child)(mf, cur_node);
207                                         *best_len_ret = best_len;
208                                         return lz_matchptr;
209                                 }
210                         }
211                 }
212
213                 if (matchptr[len] < in_next[len]) {
214                         *pending_lt_ptr = cur_node;
215                         pending_lt_ptr = TEMPLATED(bt_right_child)(mf, cur_node);
216                         cur_node = *pending_lt_ptr;
217                         best_lt_len = len;
218                         if (best_gt_len < len)
219                                 len = best_gt_len;
220                 } else {
221                         *pending_gt_ptr = cur_node;
222                         pending_gt_ptr = TEMPLATED(bt_left_child)(mf, cur_node);
223                         cur_node = *pending_gt_ptr;
224                         best_gt_len = len;
225                         if (best_lt_len < len)
226                                 len = best_lt_len;
227                 }
228
229                 if (!cur_node || !--depth_remaining) {
230                         *pending_lt_ptr = 0;
231                         *pending_gt_ptr = 0;
232                         *best_len_ret = best_len;
233                         return lz_matchptr;
234                 }
235         }
236 }
237
238 /*
239  * Retrieve a list of matches with the current position.
240  *
241  * @mf
242  *      The matchfinder structure.
243  * @in_begin
244  *      Pointer to the beginning of the input buffer.
245  * @cur_pos
246  *      The current position in the input buffer (the position of the sequence
247  *      being matched against).
248  * @max_len
249  *      The maximum permissible match length at this position.
250  * @nice_len
251  *      Stop searching if a match of at least this length is found.
252  *      Must be <= @max_len.
253  * @max_search_depth
254  *      Limit on the number of potential matches to consider.  Must be >= 1.
255  * @next_hash
256  *      Pointer to the hash code for the current sequence, which was computed
257  *      one position in advance so that the binary tree root could be
258  *      prefetched.  This is an input/output parameter.
259  * @best_len_ret
260  *      If a match of length >= 3 was found, then the length of the longest such
261  *      match is written here; otherwise 2 is written here.  (Note: this is
262  *      redundant with the 'struct lz_match' array, but this is easier for the
263  *      compiler to optimize when inlined and the caller immediately does a
264  *      check against 'best_len'.)
265  * @lz_matchptr
266  *      An array in which this function will record the matches.  The recorded
267  *      matches will be sorted by strictly increasing length and increasing
268  *      offset.  The maximum number of matches that may be found is
269  *      'min(nice_len, max_len) - 2 + 1', or one less if length 2 matches are
270  *      disabled.
271  *
272  * The return value is a pointer to the next available slot in the @lz_matchptr
273  * array.  (If no matches were found, this will be the same as @lz_matchptr.)
274  */
275 static inline struct lz_match *
276 TEMPLATED(bt_matchfinder_get_matches)(struct TEMPLATED(bt_matchfinder) *mf,
277                                       const u8 *in_begin,
278                                       ptrdiff_t cur_pos,
279                                       u32 max_len,
280                                       u32 nice_len,
281                                       u32 max_search_depth,
282                                       u32 *next_hash,
283                                       u32 *best_len_ret,
284                                       struct lz_match *lz_matchptr)
285 {
286         return TEMPLATED(bt_matchfinder_advance_one_byte)(mf,
287                                                           in_begin,
288                                                           cur_pos,
289                                                           max_len,
290                                                           nice_len,
291                                                           max_search_depth,
292                                                           next_hash,
293                                                           best_len_ret,
294                                                           lz_matchptr,
295                                                           true);
296 }
297
298 /*
299  * Advance the matchfinder, but don't record any matches.
300  *
301  * @mf
302  *      The matchfinder structure.
303  * @in_begin
304  *      Pointer to the beginning of the input buffer.
305  * @cur_pos
306  *      The current position in the input buffer.
307  * @max_len
308  *      The maximum permissible match length at this position.
309  * @nice_len
310  *      Stop searching if a match of at least this length is found.
311  * @max_search_depth
312  *      Limit on the number of potential matches to consider.
313  * @next_hash
314  *      Pointer to the hash code for the current sequence, which was computed
315  *      one position in advance so that the binary tree root could be
316  *      prefetched.  This is an input/output parameter.
317  *
318  * Note: this is very similar to bt_matchfinder_get_matches() because both
319  * functions must do hashing and tree re-rooting.  This version just doesn't
320  * actually record any matches.
321  */
322 static inline void
323 TEMPLATED(bt_matchfinder_skip_position)(struct TEMPLATED(bt_matchfinder) *mf,
324                                         const u8 *in_begin,
325                                         ptrdiff_t cur_pos,
326                                         u32 max_len,
327                                         u32 nice_len,
328                                         u32 max_search_depth,
329                                         u32 *next_hash)
330 {
331         u32 best_len;
332         TEMPLATED(bt_matchfinder_advance_one_byte)(mf,
333                                                    in_begin,
334                                                    cur_pos,
335                                                    max_len,
336                                                    nice_len,
337                                                    max_search_depth,
338                                                    next_hash,
339                                                    &best_len,
340                                                    NULL,
341                                                    false);
342 }