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