2 * bt_matchfinder.h - Lempel-Ziv matchfinding with a hash table of binary trees
4 * The following copying information applies to this specific source code file:
6 * Written in 2014-2016 by Eric Biggers <ebiggers3@gmail.com>
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").
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.
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/>.
20 * ----------------------------------------------------------------------------
22 * This is a Binary Trees (bt) based matchfinder.
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.
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.
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.
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.
55 * ----------------------------------------------------------------------------
61 #include "wimlib/lz_extend.h"
62 #include "wimlib/lz_hash.h"
64 #define BT_MATCHFINDER_HASH3_ORDER 15
65 #define BT_MATCHFINDER_HASH3_WAYS 2
66 #define BT_MATCHFINDER_HASH4_ORDER 16
68 /* TEMPLATED functions and structures have MF_SUFFIX appended to their name. */
70 #define TEMPLATED(name) CONCAT(name, MF_SUFFIX)
72 #ifndef _WIMLIB_BT_MATCHFINDER_H
73 #define _WIMLIB_BT_MATCHFINDER_H
75 /* Non-templated definitions */
77 /* Representation of a match found by the bt_matchfinder */
80 /* The number of bytes matched. */
83 /* The offset back from the current position that was matched. */
87 #endif /* _WIMLIB_BT_MATCHFINDER_H */
89 struct TEMPLATED(bt_matchfinder) {
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];
96 /* The hash table for finding length 3 matches */
97 mf_pos_t hash3_tab[1UL << BT_MATCHFINDER_HASH3_ORDER][BT_MATCHFINDER_HASH3_WAYS];
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];
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[];
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 forceinline size_t
112 TEMPLATED(bt_matchfinder_size)(size_t max_bufsize)
114 return sizeof(struct TEMPLATED(bt_matchfinder)) +
115 (2 * max_bufsize * sizeof(mf_pos_t));
118 /* Prepare the matchfinder for a new input buffer. */
119 static forceinline void
120 TEMPLATED(bt_matchfinder_init)(struct TEMPLATED(bt_matchfinder) *mf)
122 memset(mf, 0, sizeof(*mf));
125 static forceinline mf_pos_t *
126 TEMPLATED(bt_left_child)(struct TEMPLATED(bt_matchfinder) *mf, u32 node)
128 return &mf->child_tab[(node << 1) + 0];
131 static forceinline mf_pos_t *
132 TEMPLATED(bt_right_child)(struct TEMPLATED(bt_matchfinder) *mf, u32 node)
134 return &mf->child_tab[(node << 1) + 1];
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
142 /* Advance the binary tree matchfinder by one byte, optionally recording
143 * matches. @record_matches should be a compile-time constant. */
144 static forceinline 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,
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)
156 const u8 *in_next = in_begin + cur_pos;
157 u32 depth_remaining = max_search_depth;
162 #ifdef BT_MATCHFINDER_HASH2_ORDER
166 STATIC_ASSERT(BT_MATCHFINDER_HASH3_WAYS >= 1 &&
167 BT_MATCHFINDER_HASH3_WAYS <= 2);
169 #if BT_MATCHFINDER_HASH3_WAYS >= 2
173 mf_pos_t *pending_lt_ptr, *pending_gt_ptr;
174 u32 best_lt_len, best_gt_len;
178 next_seq4 = load_u32_unaligned(in_next + 1);
179 next_seq3 = loaded_u32_to_u24(next_seq4);
181 hash3 = next_hashes[0];
182 hash4 = next_hashes[1];
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]]);
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))
198 lz_matchptr->length = 2;
199 lz_matchptr->offset = in_next - &in_begin[cur_node];
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;
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];
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];
226 cur_node = mf->hash4_tab[hash4];
227 mf->hash4_tab[hash4] = cur_pos;
229 pending_lt_ptr = TEMPLATED(bt_left_child)(mf, cur_pos);
230 pending_gt_ptr = TEMPLATED(bt_right_child)(mf, cur_pos);
235 *best_len_ret = best_len;
244 matchptr = &in_begin[cur_node];
246 if (matchptr[len] == in_next[len]) {
247 len = lz_extend(in_next, matchptr, len + 1, max_len);
248 if (!record_matches || len > best_len) {
249 if (record_matches) {
251 lz_matchptr->length = len;
252 lz_matchptr->offset = in_next - matchptr;
255 if (len >= nice_len) {
256 *pending_lt_ptr = *TEMPLATED(bt_left_child)(mf, cur_node);
257 *pending_gt_ptr = *TEMPLATED(bt_right_child)(mf, cur_node);
258 *best_len_ret = best_len;
264 if (matchptr[len] < in_next[len]) {
265 *pending_lt_ptr = cur_node;
266 pending_lt_ptr = TEMPLATED(bt_right_child)(mf, cur_node);
267 cur_node = *pending_lt_ptr;
269 if (best_gt_len < len)
272 *pending_gt_ptr = cur_node;
273 pending_gt_ptr = TEMPLATED(bt_left_child)(mf, cur_node);
274 cur_node = *pending_gt_ptr;
276 if (best_lt_len < len)
280 if (!cur_node || !--depth_remaining) {
283 *best_len_ret = best_len;
290 * Retrieve a list of matches with the current position.
293 * The matchfinder structure.
295 * Pointer to the beginning of the input buffer.
297 * The current position in the input buffer (the position of the sequence
298 * being matched against).
300 * The maximum permissible match length at this position. Must be >=
301 * BT_MATCHFINDER_REQUIRED_NBYTES.
303 * Stop searching if a match of at least this length is found.
304 * Must be <= @max_len.
306 * Limit on the number of potential matches to consider. Must be >= 1.
308 * The precomputed hash codes for the sequence beginning at @in_next.
309 * These will be used and then updated with the precomputed hashcodes for
310 * the sequence beginning at @in_next + 1.
312 * If a match of length >= 4 was found, then the length of the longest such
313 * match is written here; otherwise 3 is written here. (Note: this is
314 * redundant with the 'struct lz_match' array, but this is easier for the
315 * compiler to optimize when inlined and the caller immediately does a
316 * check against 'best_len'.)
318 * An array in which this function will record the matches. The recorded
319 * matches will be sorted by strictly increasing length and (non-strictly)
320 * increasing offset. The maximum number of matches that may be found is
321 * 'nice_len - 1', or one less if length 2 matches are disabled.
323 * The return value is a pointer to the next available slot in the @lz_matchptr
324 * array. (If no matches were found, this will be the same as @lz_matchptr.)
326 static forceinline struct lz_match *
327 TEMPLATED(bt_matchfinder_get_matches)(struct TEMPLATED(bt_matchfinder) *mf,
332 u32 max_search_depth,
333 u32 next_hashes[static 2],
335 struct lz_match *lz_matchptr)
337 return TEMPLATED(bt_matchfinder_advance_one_byte)(mf,
350 * Advance the matchfinder, but don't record any matches.
352 * This is very similar to bt_matchfinder_get_matches() because both functions
353 * must do hashing and tree re-rooting.
355 static forceinline void
356 TEMPLATED(bt_matchfinder_skip_position)(struct TEMPLATED(bt_matchfinder) *mf,
360 u32 max_search_depth,
361 u32 next_hashes[static 2])
364 TEMPLATED(bt_matchfinder_advance_one_byte)(mf,