str-two-way.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /* Byte-wise substring search, using the Two-Way algorithm.
  2. Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Written by Eric Blake <ebb9@byu.net>, 2008.
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 3, or (at your option)
  8. any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License along
  14. with this program; if not, write to the Free Software Foundation,
  15. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  16. /* Before including this file, you need to include <config.h> and
  17. <string.h>, and define:
  18. RESULT_TYPE A macro that expands to the return type.
  19. AVAILABLE(h, h_l, j, n_l)
  20. A macro that returns nonzero if there are
  21. at least N_L bytes left starting at H[J].
  22. H is 'unsigned char *', H_L, J, and N_L
  23. are 'size_t'; H_L is an lvalue. For
  24. NUL-terminated searches, H_L can be
  25. modified each iteration to avoid having
  26. to compute the end of H up front.
  27. For case-insensitivity, you may optionally define:
  28. CMP_FUNC(p1, p2, l) A macro that returns 0 iff the first L
  29. characters of P1 and P2 are equal.
  30. CANON_ELEMENT(c) A macro that canonicalizes an element right after
  31. it has been fetched from one of the two strings.
  32. The argument is an 'unsigned char'; the result
  33. must be an 'unsigned char' as well.
  34. This file undefines the macros documented above, and defines
  35. LONG_NEEDLE_THRESHOLD.
  36. */
  37. #include <limits.h>
  38. #include <stdint.h>
  39. /* We use the Two-Way string matching algorithm, which guarantees
  40. linear complexity with constant space. Additionally, for long
  41. needles, we also use a bad character shift table similar to the
  42. Boyer-Moore algorithm to achieve improved (potentially sub-linear)
  43. performance.
  44. See http://www-igm.univ-mlv.fr/~lecroq/string/node26.html#SECTION00260
  45. and http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm
  46. */
  47. /* Point at which computing a bad-byte shift table is likely to be
  48. worthwhile. Small needles should not compute a table, since it
  49. adds (1 << CHAR_BIT) + NEEDLE_LEN computations of preparation for a
  50. speedup no greater than a factor of NEEDLE_LEN. The larger the
  51. needle, the better the potential performance gain. On the other
  52. hand, on non-POSIX systems with CHAR_BIT larger than eight, the
  53. memory required for the table is prohibitive. */
  54. #if CHAR_BIT < 10
  55. # define LONG_NEEDLE_THRESHOLD 32U
  56. #else
  57. # define LONG_NEEDLE_THRESHOLD SIZE_MAX
  58. #endif
  59. #ifndef MAX
  60. # define MAX(a, b) ((a < b) ? (b) : (a))
  61. #endif
  62. #ifndef CANON_ELEMENT
  63. # define CANON_ELEMENT(c) c
  64. #endif
  65. #ifndef CMP_FUNC
  66. # define CMP_FUNC memcmp
  67. #endif
  68. /* Perform a critical factorization of NEEDLE, of length NEEDLE_LEN.
  69. Return the index of the first byte in the right half, and set
  70. *PERIOD to the global period of the right half.
  71. The global period of a string is the smallest index (possibly its
  72. length) at which all remaining bytes in the string are repetitions
  73. of the prefix (the last repetition may be a subset of the prefix).
  74. When NEEDLE is factored into two halves, a local period is the
  75. length of the smallest word that shares a suffix with the left half
  76. and shares a prefix with the right half. All factorizations of a
  77. non-empty NEEDLE have a local period of at least 1 and no greater
  78. than NEEDLE_LEN.
  79. A critical factorization has the property that the local period
  80. equals the global period. All strings have at least one critical
  81. factorization with the left half smaller than the global period.
  82. And while some strings have more than one critical factorization,
  83. it is provable that with an ordered alphabet, at least one of the
  84. critical factorizations corresponds to a maximal suffix.
  85. Given an ordered alphabet, a critical factorization can be computed
  86. in linear time, with 2 * NEEDLE_LEN comparisons, by computing the
  87. shorter of two ordered maximal suffixes. The ordered maximal
  88. suffixes are determined by lexicographic comparison while tracking
  89. periodicity. */
  90. static size_t
  91. critical_factorization (const unsigned char *needle, size_t needle_len,
  92. size_t *period)
  93. {
  94. /* Index of last byte of left half. */
  95. size_t max_suffix, max_suffix_rev;
  96. size_t j; /* Index into NEEDLE for current candidate suffix. */
  97. size_t k; /* Offset into current period. */
  98. size_t p; /* Intermediate period. */
  99. unsigned char a, b; /* Current comparison bytes. */
  100. /* Special case NEEDLE_LEN of 1 or 2 (all callers already filtered
  101. out 0-length needles. */
  102. if (needle_len < 3)
  103. {
  104. *period = 1;
  105. return needle_len - 1;
  106. }
  107. /* Invariants:
  108. 1 <= j < NEEDLE_LEN - 1
  109. 0 <= max_suffix{,_rev} < j
  110. min(max_suffix, max_suffix_rev) < global period of NEEDLE
  111. 1 <= p <= global period of NEEDLE
  112. p == global period of the substring NEEDLE[max_suffix{,_rev}+1...j]
  113. 1 <= k <= p
  114. */
  115. /* Perform lexicographic search. */
  116. max_suffix = 0;
  117. j = k = p = 1;
  118. while (j + k < needle_len)
  119. {
  120. a = CANON_ELEMENT (needle[j + k]);
  121. b = CANON_ELEMENT (needle[max_suffix + k]);
  122. if (a < b)
  123. {
  124. /* Suffix is smaller, period is entire prefix so far. */
  125. j += k;
  126. k = 1;
  127. p = j - max_suffix;
  128. }
  129. else if (a == b)
  130. {
  131. /* Advance through repetition of the current period. */
  132. if (k != p)
  133. ++k;
  134. else
  135. {
  136. j += p;
  137. k = 1;
  138. }
  139. }
  140. else /* b < a */
  141. {
  142. /* Suffix is larger, start over from current location. */
  143. max_suffix = j++;
  144. k = p = 1;
  145. }
  146. }
  147. *period = p;
  148. /* Perform reverse lexicographic search. */
  149. max_suffix_rev = 0;
  150. j = k = p = 1;
  151. while (j + k < needle_len)
  152. {
  153. a = CANON_ELEMENT (needle[j + k]);
  154. b = CANON_ELEMENT (needle[max_suffix_rev + k]);
  155. if (b < a)
  156. {
  157. /* Suffix is smaller, period is entire prefix so far. */
  158. j += k;
  159. k = 1;
  160. p = j - max_suffix_rev;
  161. }
  162. else if (a == b)
  163. {
  164. /* Advance through repetition of the current period. */
  165. if (k != p)
  166. ++k;
  167. else
  168. {
  169. j += p;
  170. k = 1;
  171. }
  172. }
  173. else /* a < b */
  174. {
  175. /* Suffix is larger, start over from current location. */
  176. max_suffix_rev = j++;
  177. k = p = 1;
  178. }
  179. }
  180. /* Choose the shorter suffix. Return the index of the first byte of
  181. the right half, rather than the last byte of the left half.
  182. For some examples, 'banana' has two critical factorizations, both
  183. exposed by the two lexicographic extreme suffixes of 'anana' and
  184. 'nana', where both suffixes have a period of 2. On the other
  185. hand, with 'aab' and 'bba', both strings have a single critical
  186. factorization of the last byte, with the suffix having a period
  187. of 1. While the maximal lexicographic suffix of 'aab' is 'b',
  188. the maximal lexicographic suffix of 'bba' is 'ba', which is not a
  189. critical factorization. Conversely, the maximal reverse
  190. lexicographic suffix of 'a' works for 'bba', but not 'ab' for
  191. 'aab'. The shorter suffix of the two will always be a critical
  192. factorization. */
  193. if (max_suffix_rev + 1 < max_suffix + 1)
  194. return max_suffix + 1;
  195. *period = p;
  196. return max_suffix_rev + 1;
  197. }
  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.
  203. If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
  204. most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.
  205. If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
  206. HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. */
  207. static RETURN_TYPE
  208. two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
  209. const unsigned char *needle, size_t needle_len)
  210. {
  211. size_t i; /* Index into current byte of NEEDLE. */
  212. size_t j; /* Index into current window of HAYSTACK. */
  213. size_t period; /* The period of the right half of needle. */
  214. size_t suffix; /* The index of the right half of needle. */
  215. /* Factor the needle into two halves, such that the left half is
  216. smaller than the global period, and the right half is
  217. periodic (with a period as large as NEEDLE_LEN - suffix). */
  218. suffix = critical_factorization (needle, needle_len, &period);
  219. /* Perform the search. Each iteration compares the right half
  220. first. */
  221. if (CMP_FUNC (needle, needle + period, suffix) == 0)
  222. {
  223. /* Entire needle is periodic; a mismatch in the left half can
  224. only advance by the period, so use memory to avoid rescanning
  225. known occurrences of the period in the right half. */
  226. size_t memory = 0;
  227. j = 0;
  228. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  229. {
  230. /* Scan for matches in right half. */
  231. i = MAX (suffix, memory);
  232. while (i < needle_len && (CANON_ELEMENT (needle[i])
  233. == CANON_ELEMENT (haystack[i + j])))
  234. ++i;
  235. if (needle_len <= i)
  236. {
  237. /* Scan for matches in left half. */
  238. i = suffix - 1;
  239. while (memory < i + 1 && (CANON_ELEMENT (needle[i])
  240. == CANON_ELEMENT (haystack[i + j])))
  241. --i;
  242. if (i + 1 < memory + 1)
  243. return (RETURN_TYPE) (haystack + j);
  244. /* No match, so remember how many repetitions of period
  245. on the right half were scanned. */
  246. j += period;
  247. memory = needle_len - period;
  248. }
  249. else
  250. {
  251. j += i - suffix + 1;
  252. memory = 0;
  253. }
  254. }
  255. }
  256. else
  257. {
  258. /* The two halves of needle are distinct; no extra memory is
  259. required, and any mismatch results in a maximal shift. */
  260. period = MAX (suffix, needle_len - suffix) + 1;
  261. j = 0;
  262. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  263. {
  264. /* Scan for matches in right half. */
  265. i = suffix;
  266. while (i < needle_len && (CANON_ELEMENT (needle[i])
  267. == CANON_ELEMENT (haystack[i + j])))
  268. ++i;
  269. if (needle_len <= i)
  270. {
  271. /* Scan for matches in left half. */
  272. i = suffix - 1;
  273. while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
  274. == CANON_ELEMENT (haystack[i + j])))
  275. --i;
  276. if (i == SIZE_MAX)
  277. return (RETURN_TYPE) (haystack + j);
  278. j += period;
  279. }
  280. else
  281. j += i - suffix + 1;
  282. }
  283. }
  284. return NULL;
  285. }
  286. /* Return the first location of non-empty NEEDLE within HAYSTACK, or
  287. NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
  288. method is optimized for LONG_NEEDLE_THRESHOLD <= NEEDLE_LEN.
  289. Performance is guaranteed to be linear, with an initialization cost
  290. of 3 * NEEDLE_LEN + (1 << CHAR_BIT) operations.
  291. If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
  292. most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching,
  293. and sublinear performance O(HAYSTACK_LEN / NEEDLE_LEN) is possible.
  294. If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
  295. HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching, and
  296. sublinear performance is not possible. */
  297. static RETURN_TYPE
  298. two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
  299. const unsigned char *needle, size_t needle_len)
  300. {
  301. size_t i; /* Index into current byte of NEEDLE. */
  302. size_t j; /* Index into current window of HAYSTACK. */
  303. size_t period; /* The period of the right half of needle. */
  304. size_t suffix; /* The index of the right half of needle. */
  305. size_t shift_table[1U << CHAR_BIT]; /* See below. */
  306. /* Factor the needle into two halves, such that the left half is
  307. smaller than the global period, and the right half is
  308. periodic (with a period as large as NEEDLE_LEN - suffix). */
  309. suffix = critical_factorization (needle, needle_len, &period);
  310. /* Populate shift_table. For each possible byte value c,
  311. shift_table[c] is the distance from the last occurrence of c to
  312. the end of NEEDLE, or NEEDLE_LEN if c is absent from the NEEDLE.
  313. shift_table[NEEDLE[NEEDLE_LEN - 1]] contains the only 0. */
  314. for (i = 0; i < 1U << CHAR_BIT; i++)
  315. shift_table[i] = needle_len;
  316. for (i = 0; i < needle_len; i++)
  317. shift_table[CANON_ELEMENT (needle[i])] = needle_len - i - 1;
  318. /* Perform the search. Each iteration compares the right half
  319. first. */
  320. if (CMP_FUNC (needle, needle + period, suffix) == 0)
  321. {
  322. /* Entire needle is periodic; a mismatch in the left half can
  323. only advance by the period, so use memory to avoid rescanning
  324. known occurrences of the period in the right half. */
  325. size_t memory = 0;
  326. size_t shift;
  327. j = 0;
  328. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  329. {
  330. /* Check the last byte first; if it does not match, then
  331. shift to the next possible match location. */
  332. shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
  333. if (0 < shift)
  334. {
  335. if (memory && shift < period)
  336. {
  337. /* Since needle is periodic, but the last period has
  338. a byte out of place, there can be no match until
  339. after the mismatch. */
  340. shift = needle_len - period;
  341. memory = 0;
  342. }
  343. j += shift;
  344. continue;
  345. }
  346. /* Scan for matches in right half. The last byte has
  347. already been matched, by virtue of the shift table. */
  348. i = MAX (suffix, memory);
  349. while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
  350. == CANON_ELEMENT (haystack[i + j])))
  351. ++i;
  352. if (needle_len - 1 <= i)
  353. {
  354. /* Scan for matches in left half. */
  355. i = suffix - 1;
  356. while (memory < i + 1 && (CANON_ELEMENT (needle[i])
  357. == CANON_ELEMENT (haystack[i + j])))
  358. --i;
  359. if (i + 1 < memory + 1)
  360. return (RETURN_TYPE) (haystack + j);
  361. /* No match, so remember how many repetitions of period
  362. on the right half were scanned. */
  363. j += period;
  364. memory = needle_len - period;
  365. }
  366. else
  367. {
  368. j += i - suffix + 1;
  369. memory = 0;
  370. }
  371. }
  372. }
  373. else
  374. {
  375. /* The two halves of needle are distinct; no extra memory is
  376. required, and any mismatch results in a maximal shift. */
  377. size_t shift;
  378. period = MAX (suffix, needle_len - suffix) + 1;
  379. j = 0;
  380. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  381. {
  382. /* Check the last byte first; if it does not match, then
  383. shift to the next possible match location. */
  384. shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
  385. if (0 < shift)
  386. {
  387. j += shift;
  388. continue;
  389. }
  390. /* Scan for matches in right half. The last byte has
  391. already been matched, by virtue of the shift table. */
  392. i = suffix;
  393. while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
  394. == CANON_ELEMENT (haystack[i + j])))
  395. ++i;
  396. if (needle_len - 1 <= i)
  397. {
  398. /* Scan for matches in left half. */
  399. i = suffix - 1;
  400. while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
  401. == CANON_ELEMENT (haystack[i + j])))
  402. --i;
  403. if (i == SIZE_MAX)
  404. return (RETURN_TYPE) (haystack + j);
  405. j += period;
  406. }
  407. else
  408. j += i - suffix + 1;
  409. }
  410. }
  411. return NULL;
  412. }
  413. #undef AVAILABLE
  414. #undef CANON_ELEMENT
  415. #undef CMP_FUNC
  416. #undef MAX
  417. #undef RETURN_TYPE