1 /* Byte-wise substring search, using the Two-Way algorithm.
2 Copyright (C) 2008-2012 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Written by Eric Blake <ebb9@byu.net>, 2008.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <http://www.gnu.org/licenses/>. */
20 /* Before including this file, you need to include <string.h> (and
21 <config.h> before that, if not part of libc), and define:
22 RESULT_TYPE A macro that expands to the return type.
23 AVAILABLE(h, h_l, j, n_l)
24 A macro that returns nonzero if there are
25 at least N_L bytes left starting at H[J].
26 H is 'unsigned char *', H_L, J, and N_L
27 are 'size_t'; H_L is an lvalue. For
28 NUL-terminated searches, H_L can be
29 modified each iteration to avoid having
30 to compute the end of H up front.
32 For case-insensitivity, you may optionally define:
33 CMP_FUNC(p1, p2, l) A macro that returns 0 iff the first L
34 characters of P1 and P2 are equal.
35 CANON_ELEMENT(c) A macro that canonicalizes an element right after
36 it has been fetched from one of the two strings.
37 The argument is an 'unsigned char'; the result
38 must be an 'unsigned char' as well.
40 This file undefines the macros documented above, and defines
41 LONG_NEEDLE_THRESHOLD.
46 #include <sys/param.h> /* Defines MAX. */
48 /* We use the Two-Way string matching algorithm, which guarantees
49 linear complexity with constant space. Additionally, for long
50 needles, we also use a bad character shift table similar to the
51 Boyer-Moore algorithm to achieve improved (potentially sub-linear)
54 See http://www-igm.univ-mlv.fr/~lecroq/string/node26.html#SECTION00260
55 and http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm
58 /* Point at which computing a bad-byte shift table is likely to be
59 worthwhile. Small needles should not compute a table, since it
60 adds (1 << CHAR_BIT) + NEEDLE_LEN computations of preparation for a
61 speedup no greater than a factor of NEEDLE_LEN. The larger the
62 needle, the better the potential performance gain. On the other
63 hand, on non-POSIX systems with CHAR_BIT larger than eight, the
64 memory required for the table is prohibitive. */
66 # define LONG_NEEDLE_THRESHOLD 32U
68 # define LONG_NEEDLE_THRESHOLD SIZE_MAX
72 # define CANON_ELEMENT(c) c
75 # define CMP_FUNC memcmp
78 /* Perform a critical factorization of NEEDLE, of length NEEDLE_LEN.
79 Return the index of the first byte in the right half, and set
80 *PERIOD to the global period of the right half.
82 The global period of a string is the smallest index (possibly its
83 length) at which all remaining bytes in the string are repetitions
84 of the prefix (the last repetition may be a subset of the prefix).
86 When NEEDLE is factored into two halves, a local period is the
87 length of the smallest word that shares a suffix with the left half
88 and shares a prefix with the right half. All factorizations of a
89 non-empty NEEDLE have a local period of at least 1 and no greater
92 A critical factorization has the property that the local period
93 equals the global period. All strings have at least one critical
94 factorization with the left half smaller than the global period.
96 Given an ordered alphabet, a critical factorization can be computed
97 in linear time, with 2 * NEEDLE_LEN comparisons, by computing the
98 larger of two ordered maximal suffixes. The ordered maximal
99 suffixes are determined by lexicographic comparison of
102 critical_factorization (const unsigned char *needle, size_t needle_len,
105 /* Index of last byte of left half, or SIZE_MAX. */
106 size_t max_suffix, max_suffix_rev;
107 size_t j; /* Index into NEEDLE for current candidate suffix. */
108 size_t k; /* Offset into current period. */
109 size_t p; /* Intermediate period. */
110 unsigned char a, b; /* Current comparison bytes. */
113 0 <= j < NEEDLE_LEN - 1
114 -1 <= max_suffix{,_rev} < j (treating SIZE_MAX as if it were signed)
115 min(max_suffix, max_suffix_rev) < global period of NEEDLE
116 1 <= p <= global period of NEEDLE
117 p == global period of the substring NEEDLE[max_suffix{,_rev}+1...j]
121 /* Perform lexicographic search. */
122 max_suffix = SIZE_MAX;
125 while (j + k < needle_len)
127 a = CANON_ELEMENT (needle[j + k]);
128 b = CANON_ELEMENT (needle[max_suffix + k]);
131 /* Suffix is smaller, period is entire prefix so far. */
138 /* Advance through repetition of the current period. */
149 /* Suffix is larger, start over from current location. */
156 /* Perform reverse lexicographic search. */
157 max_suffix_rev = SIZE_MAX;
160 while (j + k < needle_len)
162 a = CANON_ELEMENT (needle[j + k]);
163 b = CANON_ELEMENT (needle[max_suffix_rev + k]);
166 /* Suffix is smaller, period is entire prefix so far. */
169 p = j - max_suffix_rev;
173 /* Advance through repetition of the current period. */
184 /* Suffix is larger, start over from current location. */
185 max_suffix_rev = j++;
190 /* Choose the longer suffix. Return the first byte of the right
191 half, rather than the last byte of the left half. */
192 if (max_suffix_rev + 1 < max_suffix + 1)
193 return max_suffix + 1;
195 return max_suffix_rev + 1;
198 /* Return the first location of non-empty NEEDLE within HAYSTACK, or
199 NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
200 method is optimized for NEEDLE_LEN < LONG_NEEDLE_THRESHOLD.
201 Performance is guaranteed to be linear, with an initialization cost
202 of 2 * NEEDLE_LEN comparisons.
204 If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
205 most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.
206 If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
207 HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. */
209 two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
210 const unsigned char *needle, size_t needle_len)
212 size_t i; /* Index into current byte of NEEDLE. */
213 size_t j; /* Index into current window of HAYSTACK. */
214 size_t period; /* The period of the right half of needle. */
215 size_t suffix; /* The index of the right half of needle. */
217 /* Factor the needle into two halves, such that the left half is
218 smaller than the global period, and the right half is
219 periodic (with a period as large as NEEDLE_LEN - suffix). */
220 suffix = critical_factorization (needle, needle_len, &period);
222 /* Perform the search. Each iteration compares the right half
224 if (CMP_FUNC (needle, needle + period, suffix) == 0)
226 /* Entire needle is periodic; a mismatch can only advance by the
227 period, so use memory to avoid rescanning known occurrences
231 while (AVAILABLE (haystack, haystack_len, j, needle_len))
233 /* Scan for matches in right half. */
234 i = MAX (suffix, memory);
235 while (i < needle_len && (CANON_ELEMENT (needle[i])
236 == CANON_ELEMENT (haystack[i + j])))
240 /* Scan for matches in left half. */
242 while (memory < i + 1 && (CANON_ELEMENT (needle[i])
243 == CANON_ELEMENT (haystack[i + j])))
245 if (i + 1 < memory + 1)
246 return (RETURN_TYPE) (haystack + j);
247 /* No match, so remember how many repetitions of period
248 on the right half were scanned. */
250 memory = needle_len - period;
261 /* The two halves of needle are distinct; no extra memory is
262 required, and any mismatch results in a maximal shift. */
263 period = MAX (suffix, needle_len - suffix) + 1;
265 while (AVAILABLE (haystack, haystack_len, j, needle_len))
267 /* Scan for matches in right half. */
269 while (i < needle_len && (CANON_ELEMENT (needle[i])
270 == CANON_ELEMENT (haystack[i + j])))
274 /* Scan for matches in left half. */
276 while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
277 == CANON_ELEMENT (haystack[i + j])))
280 return (RETURN_TYPE) (haystack + j);
290 /* Return the first location of non-empty NEEDLE within HAYSTACK, or
291 NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
292 method is optimized for LONG_NEEDLE_THRESHOLD <= NEEDLE_LEN.
293 Performance is guaranteed to be linear, with an initialization cost
294 of 3 * NEEDLE_LEN + (1 << CHAR_BIT) operations.
296 If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
297 most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching,
298 and sublinear performance O(HAYSTACK_LEN / NEEDLE_LEN) is possible.
299 If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
300 HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching, and
301 sublinear performance is not possible. */
303 two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
304 const unsigned char *needle, size_t needle_len)
306 size_t i; /* Index into current byte of NEEDLE. */
307 size_t j; /* Index into current window of HAYSTACK. */
308 size_t period; /* The period of the right half of needle. */
309 size_t suffix; /* The index of the right half of needle. */
310 size_t shift_table[1U << CHAR_BIT]; /* See below. */
312 /* Factor the needle into two halves, such that the left half is
313 smaller than the global period, and the right half is
314 periodic (with a period as large as NEEDLE_LEN - suffix). */
315 suffix = critical_factorization (needle, needle_len, &period);
317 /* Populate shift_table. For each possible byte value c,
318 shift_table[c] is the distance from the last occurrence of c to
319 the end of NEEDLE, or NEEDLE_LEN if c is absent from the NEEDLE.
320 shift_table[NEEDLE[NEEDLE_LEN - 1]] contains the only 0. */
321 for (i = 0; i < 1U << CHAR_BIT; i++)
322 shift_table[i] = needle_len;
323 for (i = 0; i < needle_len; i++)
324 shift_table[CANON_ELEMENT (needle[i])] = needle_len - i - 1;
326 /* Perform the search. Each iteration compares the right half
328 if (CMP_FUNC (needle, needle + period, suffix) == 0)
330 /* Entire needle is periodic; a mismatch can only advance by the
331 period, so use memory to avoid rescanning known occurrences
336 while (AVAILABLE (haystack, haystack_len, j, needle_len))
338 /* Check the last byte first; if it does not match, then
339 shift to the next possible match location. */
340 shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
343 if (memory && shift < period)
345 /* Since needle is periodic, but the last period has
346 a byte out of place, there can be no match until
347 after the mismatch. */
348 shift = needle_len - period;
354 /* Scan for matches in right half. The last byte has
355 already been matched, by virtue of the shift table. */
356 i = MAX (suffix, memory);
357 while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
358 == CANON_ELEMENT (haystack[i + j])))
360 if (needle_len - 1 <= i)
362 /* Scan for matches in left half. */
364 while (memory < i + 1 && (CANON_ELEMENT (needle[i])
365 == CANON_ELEMENT (haystack[i + j])))
367 if (i + 1 < memory + 1)
368 return (RETURN_TYPE) (haystack + j);
369 /* No match, so remember how many repetitions of period
370 on the right half were scanned. */
372 memory = needle_len - period;
383 /* The two halves of needle are distinct; no extra memory is
384 required, and any mismatch results in a maximal shift. */
386 period = MAX (suffix, needle_len - suffix) + 1;
388 while (AVAILABLE (haystack, haystack_len, j, needle_len))
390 /* Check the last byte first; if it does not match, then
391 shift to the next possible match location. */
392 shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
398 /* Scan for matches in right half. The last byte has
399 already been matched, by virtue of the shift table. */
401 while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
402 == CANON_ELEMENT (haystack[i + j])))
404 if (needle_len - 1 <= i)
406 /* Scan for matches in left half. */
408 while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
409 == CANON_ELEMENT (haystack[i + j])))
412 return (RETURN_TYPE) (haystack + j);