4 * Suffix array match-finder for Lempel-Ziv compression.
8 * Copyright (c) 2013, 2014 Eric Biggers. All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
25 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
30 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
31 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 #include "wimlib/divsufsort.h"
39 #include "wimlib/lz_sarray.h"
40 #include "wimlib/util.h"
43 /* If ENABLE_LZ_DEBUG is defined, verify that the suffix array satisfies its
46 * @SA The constructed suffix array.
47 * @T The original data.
48 * @found Temporary 'bool' array of length @n.
49 * @n Length of the data (length of @SA, @T, and @found arrays).
51 * WARNING: this is for debug use only as it does not necessarily run in linear
54 verify_suffix_array(const lz_sarray_pos_t SA[restrict],
59 #ifdef ENABLE_LZ_DEBUG
60 /* Ensure the SA contains exactly one of each i in [0, n - 1]. */
61 for (lz_sarray_pos_t i = 0; i < n; i++)
63 for (lz_sarray_pos_t r = 0; r < n; r++) {
64 lz_sarray_pos_t i = SA[r];
70 /* Ensure the suffix with rank r is lexicographically lesser than the
71 * suffix with rank (r + 1) for all r in [0, n - 2]. */
72 for (lz_sarray_pos_t r = 0; r < n - 1; r++) {
74 lz_sarray_pos_t i1 = SA[r];
75 lz_sarray_pos_t i2 = SA[r + 1];
77 lz_sarray_pos_t n1 = n - i1;
78 lz_sarray_pos_t n2 = n - i2;
80 int res = memcmp(&T[i1], &T[i2], min(n1, n2));
81 LZ_ASSERT(res < 0 || (res == 0 && n1 < n2));
83 #endif /* ENABLE_LZ_DEBUG */
86 /* Compute the inverse suffix array @ISA from the suffix array @SA in linear
89 * Whereas the suffix array is a mapping from suffix rank to suffix position,
90 * the inverse suffix array is a mapping from suffix position to suffix rank.
93 compute_inverse_suffix_array(lz_sarray_pos_t ISA[restrict],
94 const lz_sarray_pos_t SA[restrict],
99 for (r = 0; r < n; r++)
104 /* Compute the LCP (Longest Common Prefix) array in linear time.
106 * LCP[r] will be the length of the longest common prefix between the suffixes
107 * with positions SA[r - 1] and SA[r]. LCP[0] will be undefined.
109 * Algorithm adapted from Kasai et al. 2001: "Linear-Time Longest-Common-Prefix
110 * Computation in Suffix Arrays and Its Applications". Modified slightly to
111 * take into account that with bytes in the real world, there is no unique
112 * symbol at the end of the string. */
114 compute_lcp_array(lz_sarray_pos_t LCP[restrict],
115 const lz_sarray_pos_t SA[restrict],
116 const lz_sarray_pos_t ISA[restrict],
117 const u8 T[restrict],
120 lz_sarray_pos_t h, i, r, j, lim;
123 for (i = 0; i < n; i++) {
127 lim = min(n - i, n - j);
129 while (h < lim && T[i + h] == T[j + h])
138 /* If ENABLE_LZ_DEBUG is defined, verify that the LCP (Longest Common Prefix)
139 * array satisfies its definition.
141 * WARNING: this is for debug use only as it does not necessarily run in linear
144 verify_lcp_array(lz_sarray_pos_t LCP[restrict],
145 const lz_sarray_pos_t SA[restrict],
146 const u8 T[restrict],
149 #ifdef ENABLE_LZ_DEBUG
150 for (lz_sarray_pos_t r = 0; r < n - 1; r++) {
151 lz_sarray_pos_t i1 = SA[r];
152 lz_sarray_pos_t i2 = SA[r + 1];
153 lz_sarray_pos_t lcp = LCP[r + 1];
155 lz_sarray_pos_t n1 = n - i1;
156 lz_sarray_pos_t n2 = n - i2;
158 LZ_ASSERT(lcp <= min(n1, n2));
160 LZ_ASSERT(memcmp(&T[i1], &T[i2], lcp) == 0);
161 if (lcp < min(n1, n2))
162 LZ_ASSERT(T[i1 + lcp] != T[i2 + lcp]);
164 #endif /* ENABLE_LZ_DEBUG */
167 /* Initialize the SA link array in linear time.
169 * This is similar to computing the LPF (Longest Previous Factor) array, which
170 * is addressed in several papers. In particular the algorithms below are based
171 * on Crochemore et al. 2009: "LPF computation revisited". However, this
172 * match-finder does not actually compute or use the LPF array per se. Rather,
173 * this function sets up some information necessary to compute the LPF array,
174 * but later lz_sarray_get_matches() actually uses this information to search
175 * the suffix array directly and can keep searching beyond the first (longest)
176 * match whose length would be placed in the LPF array. This difference from
177 * the theoretical work is necessary because in many real compression formats
178 * matches take variable numbers of bits to encode, so a decent parser needs to
179 * consider more than just the longest match with unspecified offset.
181 * Note: We cap the lcpprev and lcpnext values to the maximum match length so
182 * that the match-finder need not worry about it later, in the inner loop.
184 * Note: the LCP array is one of the inputs to this function, but it is used as
185 * temporary space and therefore will be invalidated.
188 init_salink(struct salink link[restrict],
189 lz_sarray_pos_t LCP[restrict],
190 const lz_sarray_pos_t SA[restrict],
191 const u8 T[restrict],
193 lz_sarray_len_t min_match_len,
194 lz_sarray_len_t max_match_len)
196 /* Calculate salink.dist_to_next and salink.lcpnext.
198 * Pass 1 calculates, for each suffix rank, the corresponding
199 * "next_initial" value which is the smallest larger rank that
200 * corresponds to a suffix starting earlier in the string. It also
201 * calculates "lcpnext_initial", which is the longest common prefix with
202 * that suffix, although to eliminate checks in lz_sarray_get_matches(),
203 * "lcpnext_initial" is set to 0 if it's less than the minimum match
204 * length or set to the maximum match length if it's greater than the
205 * maximum match length.
207 * Pass 2 translates each absolute "next_initial", a 4-byte value, into
208 * a relative "dist_to_next", a 1-byte value. This is done to save
209 * memory. In the case that the exact relative distance cannot be
210 * encoded in 1 byte, it is capped to 255. This is valid as long as
211 * lz_sarray_get_matches() validates each position before using it.
212 * Note that "lcpnext" need not be updated in this case because it will
213 * not be used until the actual next rank has been found anyway.
215 link[n - 1].next_initial = LZ_SARRAY_POS_MAX;
216 link[n - 1].lcpnext_initial = 0;
217 for (lz_sarray_pos_t r = n - 2; r != LZ_SARRAY_POS_MAX; r--) {
218 lz_sarray_pos_t t = r + 1;
219 lz_sarray_pos_t l = LCP[t];
220 while (t != LZ_SARRAY_POS_MAX && SA[t] > SA[r]) {
221 l = min(l, link[t].lcpnext_initial);
222 t = link[t].next_initial;
224 link[r].next_initial = t;
226 if (l < min_match_len)
228 else if (l > max_match_len)
230 link[r].lcpnext_initial = l;
232 for (lz_sarray_pos_t r = 0; r < n; r++) {
233 lz_sarray_pos_t next;
235 lz_sarray_delta_t dist_to_next;
237 next = link[r].next_initial;
238 l = link[r].lcpnext_initial;
240 if (next == LZ_SARRAY_POS_MAX)
242 else if (next - r <= LZ_SARRAY_DELTA_MAX)
243 dist_to_next = next - r;
245 dist_to_next = LZ_SARRAY_DELTA_MAX;
248 link[r].dist_to_next = dist_to_next;
251 /* Calculate salink.dist_to_prev and salink.lcpprev.
253 * This is analgous to dist_to_next and lcpnext as described above, but
254 * in the other direction. That is, here we're interested in, for each
255 * rank, the largest smaller rank that corresponds to a suffix starting
256 * earlier in the string.
258 * To save memory we don't have a "prev_initial" field, but rather store
259 * those values in the LCP array. */
260 LCP[0] = LZ_SARRAY_POS_MAX;
262 for (lz_sarray_pos_t r = 1; r < n; r++) {
263 lz_sarray_pos_t t = r - 1;
264 lz_sarray_pos_t l = LCP[r];
265 while (t != LZ_SARRAY_POS_MAX && SA[t] > SA[r]) {
266 l = min(l, link[t].lcpprev);
271 if (l < min_match_len)
273 else if (l > max_match_len)
278 for (lz_sarray_pos_t r = 0; r < n; r++) {
280 lz_sarray_pos_t prev = LCP[r];
282 if (prev == LZ_SARRAY_POS_MAX)
283 link[r].dist_to_prev = 0;
284 else if (r - prev <= LZ_SARRAY_DELTA_MAX)
285 link[r].dist_to_prev = r - prev;
287 link[r].dist_to_prev = LZ_SARRAY_DELTA_MAX;
291 /* If ENABLE_LZ_DEBUG is defined, verify the values computed by init_salink().
293 * WARNING: this is for debug use only as it does not necessarily run in linear
296 verify_salink(const struct salink link[],
297 const lz_sarray_pos_t SA[],
300 lz_sarray_len_t min_match_len,
301 lz_sarray_len_t max_match_len)
303 #ifdef ENABLE_LZ_DEBUG
304 for (lz_sarray_pos_t r = 0; r < n; r++) {
305 for (lz_sarray_pos_t prev = r; ; ) {
307 LZ_ASSERT(link[r].dist_to_prev == 0);
308 LZ_ASSERT(link[r].lcpprev == 0);
314 if (SA[prev] < SA[r]) {
315 LZ_ASSERT(link[r].dist_to_prev == min(r - prev, LZ_SARRAY_DELTA_MAX));
317 lz_sarray_pos_t lcpprev;
319 lcpprev < min(n - SA[prev], n - SA[r]) &&
320 T[SA[prev] + lcpprev] == T[SA[r] + lcpprev];
323 if (lcpprev < min_match_len)
325 else if (lcpprev > max_match_len)
326 lcpprev = max_match_len;
328 LZ_ASSERT(lcpprev == link[r].lcpprev);
333 for (lz_sarray_pos_t next = r; ; ) {
335 LZ_ASSERT(link[r].dist_to_next == 0);
336 LZ_ASSERT(link[r].lcpnext == 0);
342 if (SA[next] < SA[r]) {
343 LZ_ASSERT(link[r].dist_to_next == min(next - r, LZ_SARRAY_DELTA_MAX));
345 lz_sarray_pos_t lcpnext;
347 lcpnext < min(n - SA[next], n - SA[r]) &&
348 T[SA[next] + lcpnext] == T[SA[r] + lcpnext];
351 if (lcpnext < min_match_len)
353 else if (lcpnext > max_match_len)
354 lcpnext = max_match_len;
356 LZ_ASSERT(lcpnext == link[r].lcpnext);
365 * Initialize the suffix array match-finder.
368 * The suffix array match-finder structure to initialize. This structure
369 * is expected to be zeroed before this function is called. In the case
370 * that this function fails, lz_sarray_destroy() should be called to free
371 * any memory that may have been allocated.
374 * The maximum window size to support. This must be greater than 0.
376 * The amount of needed memory will depend on this value; see
377 * lz_sarray_get_needed_memory() for details.
380 * The minimum length of each match to be found. Must be greater than 0.
383 * The maximum length of each match to be found. Must be greater than or
384 * equal to @min_match_len.
386 * @max_matches_to_consider
387 * The maximum number of matches to consider at each position. This should
388 * be greater than @max_matches_to_return because @max_matches_to_consider
389 * counts all the returned matches as well as matches of equal length to
390 * returned matches that were not returned. This parameter bounds the
391 * amount of work the match-finder does at any one position. This could be
392 * anywhere from 1 to 100+ depending on the compression ratio and
393 * performance desired.
395 * @max_matches_to_return
396 * Maximum number of matches to return at each position. Because of the
397 * suffix array search algorithm, the order in which matches are returned
398 * will be from longest to shortest, so cut-offs due to this parameter will
399 * only result in shorter matches being discarded. This parameter could be
400 * anywhere from 1 to (@max_match_len - @min_match_len + 1) depending on
401 * the compression performance desired. However, making it even moderately
402 * large (say, greater than 3) may not be very helpful due to the property
403 * that the matches are returned from longest to shortest. But the main
404 * thing to keep in mind is that if the compressor decides to output a
405 * shorter-than-possible match, ideally it would be best to choose the best
406 * match of the desired length rather than truncate a longer match to that
409 * After initialization, the suffix-array match-finder can be used for any
410 * number of input strings (windows) of length less than or equal to
411 * @max_window_size by successive calls to lz_sarray_load_window().
413 * Returns %true on success, or %false if sufficient memory could not be
414 * allocated. See the note for @max_window_size above regarding the needed
418 lz_sarray_init(struct lz_sarray *mf,
419 lz_sarray_pos_t max_window_size,
420 lz_sarray_len_t min_match_len,
421 lz_sarray_len_t max_match_len,
422 u32 max_matches_to_consider,
423 u32 max_matches_to_return)
425 LZ_ASSERT(min_match_len > 0);
426 LZ_ASSERT(max_window_size > 0);
427 LZ_ASSERT(max_match_len >= min_match_len);
429 mf->max_window_size = max_window_size;
430 mf->min_match_len = min_match_len;
431 mf->max_match_len = max_match_len;
432 mf->max_matches_to_consider = max_matches_to_consider;
433 mf->max_matches_to_return = max_matches_to_return;
435 /* SA and ISA will share the same storage block. */
436 if ((u64)2 * max_window_size * sizeof(mf->SA[0]) !=
437 2 * max_window_size * sizeof(mf->SA[0]))
439 mf->SA = MALLOC(max_window_size * sizeof(mf->SA[0]) +
440 max(DIVSUFSORT_TMP1_SIZE,
441 max_window_size * sizeof(mf->SA[0])));
445 if ((u64)max_window_size * sizeof(mf->salink[0]) !=
446 max_window_size * sizeof(mf->salink[0]))
448 mf->salink = MALLOC(max(DIVSUFSORT_TMP2_SIZE,
449 max_window_size * sizeof(mf->salink[0])));
450 if (mf->salink == NULL)
457 * Return the number of bytes of memory that lz_sarray_init() would allocate for
458 * the specified maximum window size.
460 * This should be (14 * @max_window_size) unless the type definitions have been
464 lz_sarray_get_needed_memory(lz_sarray_pos_t max_window_size)
468 /* SA and ISA: 8 bytes per position */
469 size += (u64)max_window_size * sizeof(((struct lz_sarray*)0)->SA[0]) +
470 max(DIVSUFSORT_TMP1_SIZE,
471 (u64)max_window_size * sizeof(((struct lz_sarray*)0)->SA[0]));
473 /* salink: 6 bytes per position */
474 size += max(DIVSUFSORT_TMP2_SIZE,
475 (u64)max_window_size * sizeof(((struct lz_sarray*)0)->salink[0]));
481 * Prepare the suffix array match-finder to scan the specified window for
484 * @mf Suffix array match-finder previously initialized with lz_sarray_init().
486 * @T Window, or "block", in which to find matches.
488 * @n Size of window in bytes. This must be positive and less than or equal
489 * to the @max_window_size passed to lz_sarray_init().
491 * This function runs in linear time (relative to @n).
494 lz_sarray_load_window(struct lz_sarray *mf, const u8 T[], lz_sarray_pos_t n)
496 lz_sarray_pos_t *ISA, *LCP;
498 LZ_ASSERT(n > 0 && n <= mf->max_window_size);
500 /* Compute SA (Suffix Array).
502 * divsufsort() needs temporary space --- one array with 256 spaces and
503 * one array with 65536 spaces. The implementation of divsufsort() has
504 * been modified from the original to use the provided temporary space
505 * instead of allocating its own.
507 * We also check at build-time that divsufsort() uses the same integer
508 * size expected by this code. Unfortunately, divsufsort breaks if
509 * 'sa_idx_t' is defined to be a 16-bit integer; however, that would
510 * limit blocks to only 65536 bytes anyway. */
511 BUILD_BUG_ON(sizeof(lz_sarray_pos_t) != sizeof(saidx_t));
513 divsufsort(T, mf->SA, n, (saidx_t*)&mf->SA[n], (saidx_t*)mf->salink);
515 BUILD_BUG_ON(sizeof(bool) > sizeof(mf->salink[0]));
516 verify_suffix_array(mf->SA, T, (bool*)mf->salink, n);
518 /* Compute ISA (Inverse Suffix Array) in a preliminary position.
520 * This is just a trick to save memory. Since LCP is unneeded after
521 * this function, it can be computed in any available space. The
522 * storage for the ISA is the best choice because the ISA can be built
523 * quickly in salink for now, then re-built in its real location at the
524 * end. This is probably worth it because computing the ISA from the SA
525 * is very fast, and since this match-finder is memory-hungry we'd like
526 * to save as much memory as possible. */
527 BUILD_BUG_ON(sizeof(mf->salink[0]) < sizeof(mf->ISA[0]));
528 ISA = (lz_sarray_pos_t*)mf->salink;
529 compute_inverse_suffix_array(ISA, mf->SA, n);
531 /* Compute LCP (Longest Common Prefix) array. */
533 compute_lcp_array(LCP, mf->SA, ISA, T, n);
534 verify_lcp_array(LCP, mf->SA, T, n);
536 /* Initialize suffix array links. */
537 init_salink(mf->salink, LCP, mf->SA, T, n,
538 mf->min_match_len, mf->max_match_len);
539 verify_salink(mf->salink, mf->SA, T, n,
540 mf->min_match_len, mf->max_match_len);
542 /* Compute ISA (Inverse Suffix Array) in its final position. */
544 compute_inverse_suffix_array(ISA, mf->SA, n);
546 /* Save new variables and return. */
552 /* Free memory allocated for the suffix array match-finder. */
554 lz_sarray_destroy(struct lz_sarray *mf)