]> wimlib.net Git - wimlib/blob - src/lcpit_matchfinder.c
A few cleanups and fixes from recent changes
[wimlib] / src / lcpit_matchfinder.c
1 /*
2  * lcpit_matchfinder.c
3  *
4  * A match-finder for Lempel-Ziv compression based on bottom-up construction and
5  * traversal of the Longest Common Prefix (LCP) interval tree.
6  *
7  * Author:      Eric Biggers
8  * Year:        2014, 2015
9  *
10  * The author dedicates this file to the public domain.
11  * You can do whatever you want with this file.
12  */
13
14 #ifdef HAVE_CONFIG_H
15 #  include "config.h"
16 #endif
17
18 #include <limits.h>
19
20 #include "wimlib/divsufsort.h"
21 #include "wimlib/lcpit_matchfinder.h"
22 #include "wimlib/util.h"
23
24 #define LCP_BITS                6
25 #define LCP_MAX                 (((u32)1 << LCP_BITS) - 1)
26 #define POS_MASK                (((u32)1 << (32 - LCP_BITS)) - 1)
27 #define LCP_SHIFT               (32 - LCP_BITS)
28 #define LCP_MASK                (LCP_MAX << LCP_SHIFT)
29 #define MAX_NORMAL_BUFSIZE      (POS_MASK + 1)
30
31 #define HUGE_LCP_BITS           7
32 #define HUGE_LCP_MAX            (((u32)1 << HUGE_LCP_BITS) - 1)
33 #define HUGE_LCP_SHIFT          (64 - HUGE_LCP_BITS)
34 #define HUGE_POS_MASK           0xFFFFFFFF
35 #define MAX_HUGE_BUFSIZE        ((u64)HUGE_POS_MASK + 1)
36 #define HUGE_UNVISITED_TAG      0x100000000
37
38 #define PREFETCH_SAFETY         5
39
40 /*
41  * Build the LCP (Longest Common Prefix) array in linear time.
42  *
43  * LCP[r] will be the length of the longest common prefix between the suffixes
44  * with positions SA[r - 1] and SA[r].  LCP[0] will be undefined.
45  *
46  * Algorithm taken from Kasai et al. (2001), but modified slightly:
47  *
48  *  - With bytes there is no realistic way to reserve a unique symbol for
49  *    end-of-buffer, so use explicit checks for end-of-buffer.
50  *
51  *  - For decreased memory usage and improved memory locality, pack the two
52  *    logically distinct SA and LCP arrays into a single array SA_and_LCP.
53  *
54  *  - Since SA_and_LCP is accessed randomly, improve the cache behavior by
55  *    reading several entries ahead in ISA and prefetching the upcoming
56  *    SA_and_LCP entry.
57  *
58  *  - If an LCP value is less than the minimum match length, then store 0.  This
59  *    avoids having to do comparisons against the minimum match length later.
60  *
61  *  - If an LCP value is greater than the "nice match length", then store the
62  *    "nice match length".  This caps the number of bits needed to store each
63  *    LCP value, and this caps the depth of the LCP-interval tree, without
64  *    usually hurting the compression ratio too much.
65  *
66  * References:
67  *
68  *      Kasai et al.  2001.  Linear-Time Longest-Common-Prefix Computation in
69  *      Suffix Arrays and Its Applications.  CPM '01 Proceedings of the 12th
70  *      Annual Symposium on Combinatorial Pattern Matching pp. 181-192.
71  */
72 static void
73 build_LCP(u32 SA_and_LCP[restrict], const u32 ISA[restrict],
74           const u8 T[restrict], const u32 n,
75           const u32 min_lcp, const u32 max_lcp)
76 {
77         u32 h = 0;
78         for (u32 i = 0; i < n; i++) {
79                 const u32 r = ISA[i];
80                 prefetch(&SA_and_LCP[ISA[i + PREFETCH_SAFETY]]);
81                 if (r > 0) {
82                         const u32 j = SA_and_LCP[r - 1] & POS_MASK;
83                         const u32 lim = min(n - i, n - j);
84                         while (h < lim && T[i + h] == T[j + h])
85                                 h++;
86                         u32 stored_lcp = h;
87                         if (stored_lcp < min_lcp)
88                                 stored_lcp = 0;
89                         else if (stored_lcp > max_lcp)
90                                 stored_lcp = max_lcp;
91                         SA_and_LCP[r] |= stored_lcp << LCP_SHIFT;
92                         if (h > 0)
93                                 h--;
94                 }
95         }
96 }
97
98 /*
99  * Use the suffix array accompanied with the longest-common-prefix array ---
100  * which in combination can be called the "enhanced suffix array" --- to
101  * simulate a bottom-up traversal of the corresponding suffix tree, or
102  * equivalently the lcp-interval tree.  Do so in suffix rank order, but save the
103  * superinterval references needed for later bottom-up traversal of the tree in
104  * suffix position order.
105  *
106  * To enumerate the lcp-intervals, this algorithm scans the suffix array and its
107  * corresponding LCP array linearly.  While doing so, it maintains a stack of
108  * lcp-intervals that are currently open, meaning that their left boundaries
109  * have been seen but their right boundaries have not.  The bottom of the stack
110  * is the interval which covers the entire suffix array (this has lcp=0), and
111  * the top of the stack is the deepest interval that is currently open (this has
112  * the greatest lcp of any interval on the stack).  When this algorithm opens an
113  * lcp-interval, it assigns it a unique index in intervals[] and pushes it onto
114  * the stack.  When this algorithm closes an interval, it pops it from the stack
115  * and sets the intervals[] entry of that interval to the index and lcp of that
116  * interval's superinterval, which is the new top of the stack.
117  *
118  * This algorithm also set pos_data[pos] for each suffix position 'pos' to the
119  * index and lcp of the deepest lcp-interval containing it.  Alternatively, we
120  * can interpret each suffix as being associated with a singleton lcp-interval,
121  * or leaf of the suffix tree.  With this interpretation, an entry in pos_data[]
122  * is the superinterval reference for one of these singleton lcp-intervals and
123  * therefore is not fundamentally different from an entry in intervals[].
124  *
125  * To reduce memory usage, this algorithm re-uses the suffix array's memory to
126  * store the generated intervals[] array.  This is possible because SA and LCP
127  * are accessed linearly, and no more than one interval is generated per suffix.
128  *
129  * The techniques used in this algorithm are described in various published
130  * papers.  The generation of lcp-intervals from the suffix array (SA) and the
131  * longest-common-prefix array (LCP) is given as Algorithm BottomUpTraverse in
132  * Kasai et al. (2001) and Algorithm 4.1 ("Computation of lcp-intervals") in
133  * Abouelhoda et al. (2004).  Both these papers note the equivalence between
134  * lcp-intervals (including the singleton lcp-interval for each suffix) and
135  * nodes of the suffix tree.  Abouelhoda et al. (2004) furthermore applies
136  * bottom-up traversal of the lcp-interval tree to Lempel-Ziv factorization, as
137  * does Chen at al. (2008).  Algorithm CPS1b of Chen et al. (2008) dynamically
138  * re-uses the suffix array during bottom-up traversal of the lcp-interval tree.
139  *
140  * References:
141  *
142  *      Kasai et al. Linear-Time Longest-Common-Prefix Computation in Suffix
143  *      Arrays and Its Applications.  2001.  CPM '01 Proceedings of the 12th
144  *      Annual Symposium on Combinatorial Pattern Matching pp. 181-192.
145  *
146  *      M.I. Abouelhoda, S. Kurtz, E. Ohlebusch.  2004.  Replacing Suffix Trees
147  *      With Enhanced Suffix Arrays.  Journal of Discrete Algorithms Volume 2
148  *      Issue 1, March 2004, pp. 53-86.
149  *
150  *      G. Chen, S.J. Puglisi, W.F. Smyth.  2008.  Lempel-Ziv Factorization
151  *      Using Less Time & Space.  Mathematics in Computer Science June 2008,
152  *      Volume 1, Issue 4, pp. 605-623.
153  */
154 static void
155 build_LCPIT(u32 intervals[restrict], u32 pos_data[restrict], const u32 n)
156 {
157         u32 * const SA_and_LCP = intervals;
158         u32 next_interval_idx;
159         u32 open_intervals[LCP_MAX + 1];
160         u32 *top = open_intervals;
161         u32 prev_pos = SA_and_LCP[0] & POS_MASK;
162
163         *top = 0;
164         intervals[0] = 0;
165         next_interval_idx = 1;
166
167         for (u32 r = 1; r < n; r++) {
168                 const u32 next_pos = SA_and_LCP[r] & POS_MASK;
169                 const u32 next_lcp = SA_and_LCP[r] >> LCP_SHIFT;
170                 const u32 top_lcp = *top >> LCP_SHIFT;
171
172                 if (next_lcp == top_lcp) {
173                         /* Continuing the deepest open interval  */
174                         pos_data[prev_pos] = *top;
175                 } else if (next_lcp > top_lcp) {
176                         /* Opening a new interval  */
177                         *++top = (next_lcp << LCP_SHIFT) | next_interval_idx++;
178                         pos_data[prev_pos] = *top;
179                 } else {
180                         /* Closing the deepest open interval  */
181                         pos_data[prev_pos] = *top;
182                         for (;;) {
183                                 const u32 closed_interval_idx = *top-- & POS_MASK;
184                                 const u32 superinterval_lcp = *top >> LCP_SHIFT;
185
186                                 if (next_lcp == superinterval_lcp) {
187                                         /* Continuing the superinterval */
188                                         intervals[closed_interval_idx] = *top;
189                                         break;
190                                 } else if (next_lcp > superinterval_lcp) {
191                                         /* Creating a new interval that is a
192                                          * superinterval of the one being
193                                          * closed, but still a subinterval of
194                                          * its superinterval  */
195                                         *++top = (next_lcp << LCP_SHIFT) | next_interval_idx++;
196                                         intervals[closed_interval_idx] = *top;
197                                         break;
198                                 } else {
199                                         /* Also closing the superinterval  */
200                                         intervals[closed_interval_idx] = *top;
201                                 }
202                         }
203                 }
204                 prev_pos = next_pos;
205         }
206
207         /* Close any still-open intervals.  */
208         pos_data[prev_pos] = *top;
209         for (; top > open_intervals; top--)
210                 intervals[*top & POS_MASK] = *(top - 1);
211 }
212
213 /*
214  * Advance the LCP-interval tree matchfinder by one byte.
215  *
216  * If @record_matches is true, then matches are written to the @matches array
217  * sorted by strictly decreasing length and strictly decreasing offset, and the
218  * return value is the number of matches found.  Otherwise, @matches is ignored
219  * and the return value is always 0.
220  *
221  * How this algorithm works:
222  *
223  * 'cur_pos' is the position of the current suffix, which is the suffix being
224  * matched against.  'cur_pos' starts at 0 and is incremented each time this
225  * function is called.  This function finds each suffix with position less than
226  * 'cur_pos' that shares a prefix with the current suffix, but for each distinct
227  * prefix length it finds only the suffix with the greatest position (i.e. the
228  * most recently seen in the linear traversal by position).  This function
229  * accomplishes this using the lcp-interval tree data structure that was built
230  * by build_LCPIT() and is updated dynamically by this function.
231  *
232  * The first step is to read 'pos_data[cur_pos]', which gives the index and lcp
233  * value of the deepest lcp-interval containing the current suffix --- or,
234  * equivalently, the parent of the conceptual singleton lcp-interval that
235  * contains the current suffix.
236  *
237  * The second step is to ascend the lcp-interval tree until reaching an interval
238  * that has not yet been visited, and link the intervals to the current suffix
239  * along the way.   An lcp-interval has been visited if and only if it has been
240  * linked to a suffix.  Initially, no lcp-intervals are linked to suffixes.
241  *
242  * The third step is to continue ascending the lcp-interval tree, but indirectly
243  * through suffix links rather than through the original superinterval
244  * references, and continuing to form links with the current suffix along the
245  * way.  Each suffix visited during this step, except in a special case to
246  * handle outdated suffixes, is a match which can be written to matches[].  Each
247  * intervals[] entry contains the position of the next suffix to visit, which we
248  * shall call 'match_pos'; this is the most recently seen suffix that belongs to
249  * that lcp-interval.  'pos_data[match_pos]' then contains the lcp and interval
250  * index of the next lcp-interval that should be visited.
251  *
252  * We can view these arrays as describing a new set of links that gets overlaid
253  * on top of the original superinterval references of the lcp-interval tree.
254  * Each such link can connect a node of the lcp-interval tree to an ancestor
255  * more than one generation removed.
256  *
257  * For each one-byte advance, the current position becomes the most recently
258  * seen suffix for a continuous sequence of lcp-intervals from a leaf interval
259  * to the root interval.  Conceptually, this algorithm needs to update all these
260  * nodes to link to 'cur_pos', and then update 'pos_data[cur_pos]' to a "null"
261  * link.  But actually, if some of these nodes have the same most recently seen
262  * suffix, then this algorithm just visits the pos_data[] entry for that suffix
263  * and skips over all these nodes in one step.  Updating the extra nodes is
264  * accomplished by creating a redirection from the previous suffix to the
265  * current suffix.
266  *
267  * Using this shortcutting scheme, it's possible for a suffix to become out of
268  * date, which means that it is no longer the most recently seen suffix for the
269  * lcp-interval under consideration.  This case is detected by noticing when the
270  * next lcp-interval link actually points deeper in the tree, and it is worked
271  * around by just continuing until we get to a link that actually takes us
272  * higher in the tree.  This can be described as a lazy-update scheme.
273  */
274 static inline u32
275 lcpit_advance_one_byte(const u32 cur_pos,
276                        u32 pos_data[restrict],
277                        u32 intervals[restrict],
278                        struct lz_match matches[restrict],
279                        const bool record_matches)
280 {
281         u32 lcp;
282         u32 interval_idx;
283         u32 match_pos;
284         struct lz_match *matchptr;
285
286         /* Get the deepest lcp-interval containing the current suffix. */
287         lcp = pos_data[cur_pos] >> LCP_SHIFT;
288         interval_idx = pos_data[cur_pos] & POS_MASK;
289         prefetch(&intervals[pos_data[cur_pos + 1] & POS_MASK]);
290         pos_data[cur_pos] = 0;
291
292         /* Ascend until we reach a visited interval, linking the unvisited
293          * intervals to the current suffix as we go.  */
294         while (intervals[interval_idx] & LCP_MASK) {
295                 const u32 superinterval_lcp = intervals[interval_idx] >> LCP_SHIFT;
296                 const u32 superinterval_idx = intervals[interval_idx] & POS_MASK;
297                 intervals[interval_idx] = cur_pos;
298                 lcp = superinterval_lcp;
299                 interval_idx = superinterval_idx;
300         }
301
302         match_pos = intervals[interval_idx] & POS_MASK;
303         if (match_pos == 0) {
304                 /* Ambiguous case; just don't allow matches with position 0. */
305                 if (interval_idx != 0)
306                         intervals[interval_idx] = cur_pos;
307                 return 0;
308         }
309         matchptr = matches;
310         /* Ascend indirectly via pos_data[] links.  */
311         for (;;) {
312                 u32 next_lcp;
313                 u32 next_interval_idx;
314
315                 for (;;) {
316                         next_lcp = pos_data[match_pos] >> LCP_SHIFT;
317                         next_interval_idx = pos_data[match_pos] & POS_MASK;
318                         if (next_lcp < lcp)
319                                 break;
320                         /* Suffix was out of date.  */
321                         match_pos = intervals[next_interval_idx];
322                 }
323                 intervals[interval_idx] = cur_pos;
324                 pos_data[match_pos] = (lcp << LCP_SHIFT) | interval_idx;
325                 if (record_matches) {
326                         matchptr->length = lcp;
327                         matchptr->offset = cur_pos - match_pos;
328                         matchptr++;
329                 }
330                 if (next_interval_idx == 0)
331                         break;
332                 match_pos = intervals[next_interval_idx];
333                 interval_idx = next_interval_idx;
334                 lcp = next_lcp;
335         }
336         return matchptr - matches;
337 }
338
339 /* Expand SA from 32 bits to 64 bits.  */
340 static void
341 expand_SA(void *p, u32 n)
342 {
343         typedef u32 _may_alias_attribute aliased_u32_t;
344         typedef u64 _may_alias_attribute aliased_u64_t;
345
346         aliased_u32_t *SA = p;
347         aliased_u64_t *SA64 = p;
348
349         u32 r = n - 1;
350         do {
351                 SA64[r] = SA[r];
352         } while (r--);
353 }
354
355 /* Like build_LCP(), but for buffers larger than MAX_NORMAL_BUFSIZE.  */
356 static void
357 build_LCP_huge(u64 SA_and_LCP64[restrict], const u32 ISA[restrict],
358                const u8 T[restrict], const u32 n,
359                const u32 min_lcp, const u32 max_lcp)
360 {
361         u32 h = 0;
362         for (u32 i = 0; i < n; i++) {
363                 const u32 r = ISA[i];
364                 prefetch(&SA_and_LCP64[ISA[i + PREFETCH_SAFETY]]);
365                 if (r > 0) {
366                         const u32 j = SA_and_LCP64[r - 1] & HUGE_POS_MASK;
367                         const u32 lim = min(n - i, n - j);
368                         while (h < lim && T[i + h] == T[j + h])
369                                 h++;
370                         u32 stored_lcp = h;
371                         if (stored_lcp < min_lcp)
372                                 stored_lcp = 0;
373                         else if (stored_lcp > max_lcp)
374                                 stored_lcp = max_lcp;
375                         SA_and_LCP64[r] |= (u64)stored_lcp << HUGE_LCP_SHIFT;
376                         if (h > 0)
377                                 h--;
378                 }
379         }
380 }
381
382 /*
383  * Like build_LCPIT(), but for buffers larger than MAX_NORMAL_BUFSIZE.
384  *
385  * This "huge" version is also slightly different in that the lcp value stored
386  * in each intervals[] entry is the lcp value for that interval, not its
387  * superinterval.  This lcp value stays put in intervals[] and doesn't get moved
388  * to pos_data[] during lcpit_advance_one_byte_huge().  One consequence of this
389  * is that we have to use a special flag to distinguish visited from unvisited
390  * intervals.  But overall, this scheme keeps the memory usage at 12n instead of
391  * 16n.  (The non-huge version is 8n.)
392  */
393 static void
394 build_LCPIT_huge(u64 intervals64[restrict], u32 pos_data[restrict], const u32 n)
395 {
396         u64 * const SA_and_LCP64 = intervals64;
397         u32 next_interval_idx;
398         u32 open_intervals[HUGE_LCP_MAX + 1];
399         u32 *top = open_intervals;
400         u32 prev_pos = SA_and_LCP64[0] & HUGE_POS_MASK;
401
402         *top = 0;
403         intervals64[0] = 0;
404         next_interval_idx = 1;
405
406         for (u32 r = 1; r < n; r++) {
407                 const u32 next_pos = SA_and_LCP64[r] & HUGE_POS_MASK;
408                 const u32 next_lcp = SA_and_LCP64[r] >> HUGE_LCP_SHIFT;
409                 const u32 top_lcp = intervals64[*top] >> HUGE_LCP_SHIFT;
410
411                 if (next_lcp == top_lcp) {
412                         /* Continuing the deepest open interval  */
413                         pos_data[prev_pos] = *top;
414                 } else if (next_lcp > top_lcp) {
415                         /* Opening a new interval  */
416                         intervals64[next_interval_idx] = (u64)next_lcp << HUGE_LCP_SHIFT;
417                         pos_data[prev_pos] = next_interval_idx;
418                         *++top = next_interval_idx++;
419                 } else {
420                         /* Closing the deepest open interval  */
421                         pos_data[prev_pos] = *top;
422                         for (;;) {
423                                 const u32 closed_interval_idx = *top--;
424                                 const u32 superinterval_lcp = intervals64[*top] >> HUGE_LCP_SHIFT;
425
426                                 if (next_lcp == superinterval_lcp) {
427                                         /* Continuing the superinterval */
428                                         intervals64[closed_interval_idx] |=
429                                                 HUGE_UNVISITED_TAG | *top;
430                                         break;
431                                 } else if (next_lcp > superinterval_lcp) {
432                                         /* Creating a new interval that is a
433                                          * superinterval of the one being
434                                          * closed, but still a subinterval of
435                                          * its superinterval  */
436                                         intervals64[next_interval_idx] =
437                                                 (u64)next_lcp << HUGE_LCP_SHIFT;
438                                         intervals64[closed_interval_idx] |=
439                                                 HUGE_UNVISITED_TAG | next_interval_idx;
440                                         *++top = next_interval_idx++;
441                                         break;
442                                 } else {
443                                         /* Also closing the superinterval  */
444                                         intervals64[closed_interval_idx] |=
445                                                 HUGE_UNVISITED_TAG | *top;
446                                 }
447                         }
448                 }
449                 prev_pos = next_pos;
450         }
451
452         /* Close any still-open intervals.  */
453         pos_data[prev_pos] = *top;
454         for (; top > open_intervals; top--)
455                 intervals64[*top] |= HUGE_UNVISITED_TAG | *(top - 1);
456 }
457
458 /* Like lcpit_advance_one_byte(), but for buffers larger than
459  * MAX_NORMAL_BUFSIZE.  */
460 static inline u32
461 lcpit_advance_one_byte_huge(const u32 cur_pos,
462                             u32 pos_data[restrict],
463                             u64 intervals64[restrict],
464                             struct lz_match matches[restrict],
465                             const bool record_matches)
466 {
467         u32 interval_idx;
468         u32 lcp;
469         u32 match_pos;
470         struct lz_match *matchptr;
471
472         interval_idx = pos_data[cur_pos];
473         prefetch(&intervals64[pos_data[cur_pos + 1]]);
474         pos_data[cur_pos] = 0;
475
476         while (intervals64[interval_idx] & HUGE_UNVISITED_TAG) {
477                 lcp = intervals64[interval_idx] >> HUGE_LCP_SHIFT;
478                 if (lcp == 0)
479                         return 0;
480                 const u32 superinterval_idx = intervals64[interval_idx] & HUGE_POS_MASK;
481                 intervals64[interval_idx] = ((u64)lcp << HUGE_LCP_SHIFT) | cur_pos;
482                 interval_idx = superinterval_idx;
483         }
484
485         match_pos = intervals64[interval_idx] & HUGE_POS_MASK;
486         lcp = intervals64[interval_idx] >> HUGE_LCP_SHIFT;
487         matchptr = matches;
488         while (lcp != 0) {
489                 u32 next_interval_idx;
490                 u32 next_lcp;
491
492                 for (;;) {
493                         next_interval_idx = pos_data[match_pos];
494                         next_lcp = intervals64[next_interval_idx] >> HUGE_LCP_SHIFT;
495                         if (next_lcp < lcp)
496                                 break;
497                         match_pos = intervals64[next_interval_idx] & HUGE_POS_MASK;
498                 }
499                 intervals64[interval_idx] = ((u64)lcp << HUGE_LCP_SHIFT) | cur_pos;
500                 pos_data[match_pos] = interval_idx;
501                 if (record_matches) {
502                         matchptr->length = lcp;
503                         matchptr->offset = cur_pos - match_pos;
504                         matchptr++;
505                 }
506                 match_pos = intervals64[next_interval_idx] & HUGE_POS_MASK;
507                 interval_idx = next_interval_idx;
508                 lcp = next_lcp;
509         }
510         return matchptr - matches;
511 }
512
513 static inline u64
514 get_pos_data_size(size_t max_bufsize)
515 {
516         return (u64)max((u64)max_bufsize + PREFETCH_SAFETY,
517                         DIVSUFSORT_TMP_LEN) * sizeof(u32);
518 }
519
520 static inline u64
521 get_intervals_size(size_t max_bufsize)
522 {
523         return (u64)max_bufsize * (max_bufsize <= MAX_NORMAL_BUFSIZE ?
524                                    sizeof(u32) : sizeof(u64));
525 }
526
527 /*
528  * Calculate the number of bytes of memory needed for the LCP-interval tree
529  * matchfinder.
530  *
531  * @max_bufsize - maximum buffer size to support
532  *
533  * Returns the number of bytes required.
534  */
535 u64
536 lcpit_matchfinder_get_needed_memory(size_t max_bufsize)
537 {
538         return get_pos_data_size(max_bufsize) + get_intervals_size(max_bufsize);
539 }
540
541 /*
542  * Initialize the LCP-interval tree matchfinder.
543  *
544  * @mf - the matchfinder structure to initialize
545  * @max_bufsize - maximum buffer size to support
546  * @min_match_len - minimum match length in bytes
547  * @nice_match_len - only consider this many bytes of each match
548  *
549  * Returns true if successfully initialized; false if out of memory.
550  */
551 bool
552 lcpit_matchfinder_init(struct lcpit_matchfinder *mf, size_t max_bufsize,
553                        u32 min_match_len, u32 nice_match_len)
554 {
555         if (lcpit_matchfinder_get_needed_memory(max_bufsize) > SIZE_MAX)
556                 return false;
557         if (max_bufsize > MAX_HUGE_BUFSIZE - PREFETCH_SAFETY)
558                 return false;
559
560         mf->pos_data = MALLOC(get_pos_data_size(max_bufsize));
561         mf->intervals = MALLOC(get_intervals_size(max_bufsize));
562         if (!mf->pos_data || !mf->intervals) {
563                 lcpit_matchfinder_destroy(mf);
564                 return false;
565         }
566
567         mf->min_match_len = min_match_len;
568         mf->nice_match_len = min(nice_match_len,
569                                  (max_bufsize <= MAX_NORMAL_BUFSIZE) ?
570                                  LCP_MAX : HUGE_LCP_MAX);
571         for (u32 i = 0; i < PREFETCH_SAFETY; i++)
572                 mf->pos_data[max_bufsize + i] = 0;
573         return true;
574 }
575
576 /*
577  * Build the suffix array SA for the specified byte array T of length n.
578  *
579  * The suffix array is a sorted array of the byte array's suffixes, represented
580  * by indices into the byte array.  It can equivalently be viewed as a mapping
581  * from suffix rank to suffix position.
582  *
583  * To build the suffix array, we use libdivsufsort, which uses an
584  * induced-sorting-based algorithm.  In practice, this seems to be the fastest
585  * suffix array construction algorithm currently available.
586  *
587  * References:
588  *
589  *      Y. Mori.  libdivsufsort, a lightweight suffix-sorting library.
590  *      https://code.google.com/p/libdivsufsort/.
591  *
592  *      G. Nong, S. Zhang, and W.H. Chan.  2009.  Linear Suffix Array
593  *      Construction by Almost Pure Induced-Sorting.  Data Compression
594  *      Conference, 2009.  DCC '09.  pp. 193 - 202.
595  *
596  *      S.J. Puglisi, W.F. Smyth, and A. Turpin.  2007.  A Taxonomy of Suffix
597  *      Array Construction Algorithms.  ACM Computing Surveys (CSUR) Volume 39
598  *      Issue 2, 2007 Article No. 4.
599  */
600 static void
601 build_SA(u32 SA[], const u8 T[], u32 n, u32 *tmp)
602 {
603         /* Note: divsufsort() requires a fixed amount of temporary space.  The
604          * implementation of divsufsort() has been modified from the original to
605          * use the provided temporary space instead of allocating its own, since
606          * we don't want to have to deal with malloc() failures here.  */
607         divsufsort(T, SA, n, tmp);
608 }
609
610 /*
611  * Build the inverse suffix array ISA from the suffix array SA.
612  *
613  * Whereas the suffix array is a mapping from suffix rank to suffix position,
614  * the inverse suffix array is a mapping from suffix position to suffix rank.
615  */
616 static void
617 build_ISA(u32 ISA[restrict], const u32 SA[restrict], u32 n)
618 {
619         for (u32 r = 0; r < n; r++)
620                 ISA[SA[r]] = r;
621 }
622
623 /*
624  * Prepare the LCP-interval tree matchfinder for a new input buffer.
625  *
626  * @mf - the initialized matchfinder structure
627  * @T - the input buffer
628  * @n - size of the input buffer in bytes.  This must be nonzero and can be at
629  *      most the max_bufsize with which lcpit_matchfinder_init() was called.
630  */
631 void
632 lcpit_matchfinder_load_buffer(struct lcpit_matchfinder *mf, const u8 *T, u32 n)
633 {
634         /* intervals[] temporarily stores SA and LCP packed together.
635          * pos_data[] temporarily stores ISA.
636          * pos_data[] is also used as the temporary space for divsufsort().  */
637
638         build_SA(mf->intervals, T, n, mf->pos_data);
639         build_ISA(mf->pos_data, mf->intervals, n);
640         if (n <= MAX_NORMAL_BUFSIZE) {
641                 build_LCP(mf->intervals, mf->pos_data, T, n,
642                           mf->min_match_len, mf->nice_match_len);
643                 build_LCPIT(mf->intervals, mf->pos_data, n);
644                 mf->huge_mode = false;
645         } else {
646                 expand_SA(mf->intervals, n);
647                 build_LCP_huge(mf->intervals64, mf->pos_data, T, n,
648                                mf->min_match_len, mf->nice_match_len);
649                 build_LCPIT_huge(mf->intervals64, mf->pos_data, n);
650                 mf->huge_mode = true;
651         }
652         mf->cur_pos = 0; /* starting at beginning of input buffer  */
653 }
654
655 /*
656  * Retrieve a list of matches with the next position.
657  *
658  * The matches will be recorded in the @matches array, ordered by strictly
659  * decreasing length and strictly decreasing offset.
660  *
661  * The return value is the number of matches found and written to @matches.
662  * This can be any value in [0, nice_match_len - min_match_len + 1].
663  */
664 u32
665 lcpit_matchfinder_get_matches(struct lcpit_matchfinder *mf,
666                               struct lz_match *matches)
667 {
668         if (mf->huge_mode)
669                 return lcpit_advance_one_byte_huge(mf->cur_pos++, mf->pos_data,
670                                                    mf->intervals64, matches, true);
671         else
672                 return lcpit_advance_one_byte(mf->cur_pos++, mf->pos_data,
673                                               mf->intervals, matches, true);
674 }
675
676 /*
677  * Skip the next @count bytes (don't search for matches at them).  @count is
678  * assumed to be > 0.
679  */
680 void
681 lcpit_matchfinder_skip_bytes(struct lcpit_matchfinder *mf, u32 count)
682 {
683         if (mf->huge_mode) {
684                 do {
685                         lcpit_advance_one_byte_huge(mf->cur_pos++, mf->pos_data,
686                                                     mf->intervals64, NULL, false);
687                 } while (--count);
688         } else {
689                 do {
690                         lcpit_advance_one_byte(mf->cur_pos++, mf->pos_data,
691                                                mf->intervals, NULL, false);
692                 } while (--count);
693         }
694 }
695
696 /*
697  * Destroy an LCP-interval tree matchfinder that was previously initialized with
698  * lcpit_matchfinder_init().
699  */
700 void
701 lcpit_matchfinder_destroy(struct lcpit_matchfinder *mf)
702 {
703         FREE(mf->pos_data);
704         FREE(mf->intervals);
705 }