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