2 * bt_matchfinder.h - Lempel-Ziv matchfinding with a hash table of binary trees
4 * Copyright 2022 Eric Biggers
6 * Permission is hereby granted, free of charge, to any person
7 * obtaining a copy of this software and associated documentation
8 * files (the "Software"), to deal in the Software without
9 * restriction, including without limitation the rights to use,
10 * copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following
15 * The above copyright notice and this permission notice shall be
16 * included in all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 * OTHER DEALINGS IN THE SOFTWARE.
27 * ----------------------------------------------------------------------------
29 * This is a Binary Trees (bt) based matchfinder.
31 * The main data structure is a hash table where each hash bucket contains a
32 * binary tree of sequences whose first 4 bytes share the same hash code. Each
33 * sequence is identified by its starting position in the input buffer. Each
34 * binary tree is always sorted such that each left child represents a sequence
35 * lexicographically lesser than its parent and each right child represents a
36 * sequence lexicographically greater than its parent.
38 * The algorithm processes the input buffer sequentially. At each byte
39 * position, the hash code of the first 4 bytes of the sequence beginning at
40 * that position (the sequence being matched against) is computed. This
41 * identifies the hash bucket to use for that position. Then, a new binary tree
42 * node is created to represent the current sequence. Then, in a single tree
43 * traversal, the hash bucket's binary tree is searched for matches and is
44 * re-rooted at the new node.
46 * Compared to the simpler algorithm that uses linked lists instead of binary
47 * trees (see hc_matchfinder.h), the binary tree version gains more information
48 * at each node visitation. Ideally, the binary tree version will examine only
49 * 'log(n)' nodes to find the same matches that the linked list version will
50 * find by examining 'n' nodes. In addition, the binary tree version can
51 * examine fewer bytes at each node by taking advantage of the common prefixes
52 * that result from the sort order, whereas the linked list version may have to
53 * examine up to the full length of the match at each node.
55 * However, it is not always best to use the binary tree version. It requires
56 * nearly twice as much memory as the linked list version, and it takes time to
57 * keep the binary trees sorted, even at positions where the compressor does not
58 * need matches. Generally, when doing fast compression on small buffers,
59 * binary trees are the wrong approach. They are best suited for thorough
60 * compression and/or large buffers.
62 * ----------------------------------------------------------------------------
68 #include "wimlib/lz_extend.h"
69 #include "wimlib/lz_hash.h"
71 #define BT_MATCHFINDER_HASH3_ORDER 15
72 #define BT_MATCHFINDER_HASH3_WAYS 2
73 #define BT_MATCHFINDER_HASH4_ORDER 16
75 /* TEMPLATED functions and structures have MF_SUFFIX appended to their name. */
77 #define TEMPLATED(name) CONCAT(name, MF_SUFFIX)
79 #ifndef _WIMLIB_BT_MATCHFINDER_H
80 #define _WIMLIB_BT_MATCHFINDER_H
82 /* Non-templated definitions */
84 /* Representation of a match found by the bt_matchfinder */
87 /* The number of bytes matched. */
90 /* The offset back from the current position that was matched. */
94 #endif /* _WIMLIB_BT_MATCHFINDER_H */
96 struct TEMPLATED(bt_matchfinder) {
98 /* The hash table for finding length 2 matches, if enabled */
99 #ifdef BT_MATCHFINDER_HASH2_ORDER
100 mf_pos_t hash2_tab[1UL << BT_MATCHFINDER_HASH2_ORDER];
103 /* The hash table for finding length 3 matches */
104 mf_pos_t hash3_tab[1UL << BT_MATCHFINDER_HASH3_ORDER][BT_MATCHFINDER_HASH3_WAYS];
106 /* The hash table which contains the roots of the binary trees for
107 * finding length 4+ matches */
108 mf_pos_t hash4_tab[1UL << BT_MATCHFINDER_HASH4_ORDER];
110 /* The child node references for the binary trees. The left and right
111 * children of the node for the sequence with position 'pos' are
112 * 'child_tab[pos * 2]' and 'child_tab[pos * 2 + 1]', respectively. */
113 mf_pos_t child_tab[];
116 /* Return the number of bytes that must be allocated for a 'bt_matchfinder' that
117 * can work with buffers up to the specified size. */
118 static forceinline size_t
119 TEMPLATED(bt_matchfinder_size)(size_t max_bufsize)
121 return sizeof(struct TEMPLATED(bt_matchfinder)) +
122 (2 * max_bufsize * sizeof(mf_pos_t));
125 /* Prepare the matchfinder for a new input buffer. */
126 static forceinline void
127 TEMPLATED(bt_matchfinder_init)(struct TEMPLATED(bt_matchfinder) *mf)
129 memset(mf, 0, sizeof(*mf));
132 static forceinline mf_pos_t *
133 TEMPLATED(bt_left_child)(struct TEMPLATED(bt_matchfinder) *mf, u32 node)
135 return &mf->child_tab[(node << 1) + 0];
138 static forceinline mf_pos_t *
139 TEMPLATED(bt_right_child)(struct TEMPLATED(bt_matchfinder) *mf, u32 node)
141 return &mf->child_tab[(node << 1) + 1];
144 /* The minimum permissible value of 'max_len' for bt_matchfinder_get_matches()
145 * and bt_matchfinder_skip_position(). There must be sufficiently many bytes
146 * remaining to load a 32-bit integer from the *next* position. */
147 #define BT_MATCHFINDER_REQUIRED_NBYTES 5
149 /* Advance the binary tree matchfinder by one byte, optionally recording
150 * matches. @record_matches should be a compile-time constant. */
151 static forceinline struct lz_match *
152 TEMPLATED(bt_matchfinder_advance_one_byte)(struct TEMPLATED(bt_matchfinder) * const restrict mf,
153 const u8 * const restrict in_begin,
154 const ptrdiff_t cur_pos,
157 const u32 max_search_depth,
158 u32 next_hashes[const restrict static 2],
159 u32 * const restrict best_len_ret,
160 struct lz_match * restrict lz_matchptr,
161 const bool record_matches)
163 const u8 *in_next = in_begin + cur_pos;
164 u32 depth_remaining = max_search_depth;
169 #ifdef BT_MATCHFINDER_HASH2_ORDER
173 STATIC_ASSERT(BT_MATCHFINDER_HASH3_WAYS >= 1 &&
174 BT_MATCHFINDER_HASH3_WAYS <= 2);
176 #if BT_MATCHFINDER_HASH3_WAYS >= 2
180 mf_pos_t *pending_lt_ptr, *pending_gt_ptr;
181 u32 best_lt_len, best_gt_len;
185 next_seq4 = load_u32_unaligned(in_next + 1);
186 next_seq3 = loaded_u32_to_u24(next_seq4);
188 hash3 = next_hashes[0];
189 hash4 = next_hashes[1];
191 next_hashes[0] = lz_hash(next_seq3, BT_MATCHFINDER_HASH3_ORDER);
192 next_hashes[1] = lz_hash(next_seq4, BT_MATCHFINDER_HASH4_ORDER);
193 prefetchw(&mf->hash3_tab[next_hashes[0]]);
194 prefetchw(&mf->hash4_tab[next_hashes[1]]);
196 #ifdef BT_MATCHFINDER_HASH2_ORDER
197 seq2 = load_u16_unaligned(in_next);
198 hash2 = lz_hash(seq2, BT_MATCHFINDER_HASH2_ORDER);
199 cur_node = mf->hash2_tab[hash2];
200 mf->hash2_tab[hash2] = cur_pos;
201 if (record_matches &&
202 seq2 == load_u16_unaligned(&in_begin[cur_node]) &&
203 likely(in_next != in_begin))
205 lz_matchptr->length = 2;
206 lz_matchptr->offset = in_next - &in_begin[cur_node];
211 cur_node = mf->hash3_tab[hash3][0];
212 mf->hash3_tab[hash3][0] = cur_pos;
213 #if BT_MATCHFINDER_HASH3_WAYS >= 2
214 cur_node_2 = mf->hash3_tab[hash3][1];
215 mf->hash3_tab[hash3][1] = cur_node;
217 if (record_matches && likely(in_next != in_begin)) {
218 u32 seq3 = load_u24_unaligned(in_next);
219 if (seq3 == load_u24_unaligned(&in_begin[cur_node])) {
220 lz_matchptr->length = 3;
221 lz_matchptr->offset = in_next - &in_begin[cur_node];
224 #if BT_MATCHFINDER_HASH3_WAYS >= 2
225 else if (seq3 == load_u24_unaligned(&in_begin[cur_node_2])) {
226 lz_matchptr->length = 3;
227 lz_matchptr->offset = in_next - &in_begin[cur_node_2];
233 cur_node = mf->hash4_tab[hash4];
234 mf->hash4_tab[hash4] = cur_pos;
236 pending_lt_ptr = TEMPLATED(bt_left_child)(mf, cur_pos);
237 pending_gt_ptr = TEMPLATED(bt_right_child)(mf, cur_pos);
242 *best_len_ret = best_len;
251 matchptr = &in_begin[cur_node];
253 if (matchptr[len] == in_next[len]) {
254 len = lz_extend(in_next, matchptr, len + 1, max_len);
255 if (!record_matches || len > best_len) {
256 if (record_matches) {
258 lz_matchptr->length = len;
259 lz_matchptr->offset = in_next - matchptr;
262 if (len >= nice_len) {
263 *pending_lt_ptr = *TEMPLATED(bt_left_child)(mf, cur_node);
264 *pending_gt_ptr = *TEMPLATED(bt_right_child)(mf, cur_node);
265 *best_len_ret = best_len;
271 if (matchptr[len] < in_next[len]) {
272 *pending_lt_ptr = cur_node;
273 pending_lt_ptr = TEMPLATED(bt_right_child)(mf, cur_node);
274 cur_node = *pending_lt_ptr;
276 if (best_gt_len < len)
279 *pending_gt_ptr = cur_node;
280 pending_gt_ptr = TEMPLATED(bt_left_child)(mf, cur_node);
281 cur_node = *pending_gt_ptr;
283 if (best_lt_len < len)
287 if (!cur_node || !--depth_remaining) {
290 *best_len_ret = best_len;
297 * Retrieve a list of matches with the current position.
300 * The matchfinder structure.
302 * Pointer to the beginning of the input buffer.
304 * The current position in the input buffer (the position of the sequence
305 * being matched against).
307 * The maximum permissible match length at this position. Must be >=
308 * BT_MATCHFINDER_REQUIRED_NBYTES.
310 * Stop searching if a match of at least this length is found.
311 * Must be <= @max_len.
313 * Limit on the number of potential matches to consider. Must be >= 1.
315 * The precomputed hash codes for the sequence beginning at @in_next.
316 * These will be used and then updated with the precomputed hashcodes for
317 * the sequence beginning at @in_next + 1.
319 * If a match of length >= 4 was found, then the length of the longest such
320 * match is written here; otherwise 3 is written here. (Note: this is
321 * redundant with the 'struct lz_match' array, but this is easier for the
322 * compiler to optimize when inlined and the caller immediately does a
323 * check against 'best_len'.)
325 * An array in which this function will record the matches. The recorded
326 * matches will be sorted by strictly increasing length and (non-strictly)
327 * increasing offset. The maximum number of matches that may be found is
328 * 'nice_len - 1', or one less if length 2 matches are disabled.
330 * The return value is a pointer to the next available slot in the @lz_matchptr
331 * array. (If no matches were found, this will be the same as @lz_matchptr.)
333 static forceinline struct lz_match *
334 TEMPLATED(bt_matchfinder_get_matches)(struct TEMPLATED(bt_matchfinder) *mf,
339 u32 max_search_depth,
340 u32 next_hashes[static 2],
342 struct lz_match *lz_matchptr)
344 return TEMPLATED(bt_matchfinder_advance_one_byte)(mf,
357 * Advance the matchfinder, but don't record any matches.
359 * This is very similar to bt_matchfinder_get_matches() because both functions
360 * must do hashing and tree re-rooting.
362 static forceinline void
363 TEMPLATED(bt_matchfinder_skip_position)(struct TEMPLATED(bt_matchfinder) *mf,
367 u32 max_search_depth,
368 u32 next_hashes[static 2])
371 TEMPLATED(bt_matchfinder_advance_one_byte)(mf,