str-two-way.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. Given an ordered alphabet, a critical factorization can be computed
  83. in linear time, with 2 * NEEDLE_LEN comparisons, by computing the
  84. larger of two ordered maximal suffixes. The ordered maximal
  85. suffixes are determined by lexicographic comparison of
  86. periodicity. */
  87. static size_t
  88. critical_factorization (const unsigned char *needle, size_t needle_len,
  89. size_t *period)
  90. {
  91. /* Index of last byte of left half, or SIZE_MAX. */
  92. size_t max_suffix, max_suffix_rev;
  93. size_t j; /* Index into NEEDLE for current candidate suffix. */
  94. size_t k; /* Offset into current period. */
  95. size_t p; /* Intermediate period. */
  96. unsigned char a, b; /* Current comparison bytes. */
  97. /* Invariants:
  98. 0 <= j < NEEDLE_LEN - 1
  99. -1 <= max_suffix{,_rev} < j (treating SIZE_MAX as if it were signed)
  100. min(max_suffix, max_suffix_rev) < global period of NEEDLE
  101. 1 <= p <= global period of NEEDLE
  102. p == global period of the substring NEEDLE[max_suffix{,_rev}+1...j]
  103. 1 <= k <= p
  104. */
  105. /* Perform lexicographic search. */
  106. max_suffix = SIZE_MAX;
  107. j = 0;
  108. k = p = 1;
  109. while (j + k < needle_len)
  110. {
  111. a = CANON_ELEMENT (needle[j + k]);
  112. b = CANON_ELEMENT (needle[max_suffix + k]);
  113. if (a < b)
  114. {
  115. /* Suffix is smaller, period is entire prefix so far. */
  116. j += k;
  117. k = 1;
  118. p = j - max_suffix;
  119. }
  120. else if (a == b)
  121. {
  122. /* Advance through repetition of the current period. */
  123. if (k != p)
  124. ++k;
  125. else
  126. {
  127. j += p;
  128. k = 1;
  129. }
  130. }
  131. else /* b < a */
  132. {
  133. /* Suffix is larger, start over from current location. */
  134. max_suffix = j++;
  135. k = p = 1;
  136. }
  137. }
  138. *period = p;
  139. /* Perform reverse lexicographic search. */
  140. max_suffix_rev = SIZE_MAX;
  141. j = 0;
  142. k = p = 1;
  143. while (j + k < needle_len)
  144. {
  145. a = CANON_ELEMENT (needle[j + k]);
  146. b = CANON_ELEMENT (needle[max_suffix_rev + k]);
  147. if (b < a)
  148. {
  149. /* Suffix is smaller, period is entire prefix so far. */
  150. j += k;
  151. k = 1;
  152. p = j - max_suffix_rev;
  153. }
  154. else if (a == b)
  155. {
  156. /* Advance through repetition of the current period. */
  157. if (k != p)
  158. ++k;
  159. else
  160. {
  161. j += p;
  162. k = 1;
  163. }
  164. }
  165. else /* a < b */
  166. {
  167. /* Suffix is larger, start over from current location. */
  168. max_suffix_rev = j++;
  169. k = p = 1;
  170. }
  171. }
  172. /* Choose the longer suffix. Return the first byte of the right
  173. half, rather than the last byte of the left half. */
  174. if (max_suffix_rev + 1 < max_suffix + 1)
  175. return max_suffix + 1;
  176. *period = p;
  177. return max_suffix_rev + 1;
  178. }
  179. /* Return the first location of non-empty NEEDLE within HAYSTACK, or
  180. NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
  181. method is optimized for NEEDLE_LEN < LONG_NEEDLE_THRESHOLD.
  182. Performance is guaranteed to be linear, with an initialization cost
  183. of 2 * NEEDLE_LEN comparisons.
  184. If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
  185. most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.
  186. If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
  187. HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. */
  188. static RETURN_TYPE
  189. two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
  190. const unsigned char *needle, size_t needle_len)
  191. {
  192. size_t i; /* Index into current byte of NEEDLE. */
  193. size_t j; /* Index into current window of HAYSTACK. */
  194. size_t period; /* The period of the right half of needle. */
  195. size_t suffix; /* The index of the right half of needle. */
  196. /* Factor the needle into two halves, such that the left half is
  197. smaller than the global period, and the right half is
  198. periodic (with a period as large as NEEDLE_LEN - suffix). */
  199. suffix = critical_factorization (needle, needle_len, &period);
  200. /* Perform the search. Each iteration compares the right half
  201. first. */
  202. if (CMP_FUNC (needle, needle + period, suffix) == 0)
  203. {
  204. /* Entire needle is periodic; a mismatch can only advance by the
  205. period, so use memory to avoid rescanning known occurrences
  206. of the period. */
  207. size_t memory = 0;
  208. j = 0;
  209. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  210. {
  211. /* Scan for matches in right half. */
  212. i = MAX (suffix, memory);
  213. while (i < needle_len && (CANON_ELEMENT (needle[i])
  214. == CANON_ELEMENT (haystack[i + j])))
  215. ++i;
  216. if (needle_len <= i)
  217. {
  218. /* Scan for matches in left half. */
  219. i = suffix - 1;
  220. while (memory < i + 1 && (CANON_ELEMENT (needle[i])
  221. == CANON_ELEMENT (haystack[i + j])))
  222. --i;
  223. if (i + 1 < memory + 1)
  224. return (RETURN_TYPE) (haystack + j);
  225. /* No match, so remember how many repetitions of period
  226. on the right half were scanned. */
  227. j += period;
  228. memory = needle_len - period;
  229. }
  230. else
  231. {
  232. j += i - suffix + 1;
  233. memory = 0;
  234. }
  235. }
  236. }
  237. else
  238. {
  239. /* The two halves of needle are distinct; no extra memory is
  240. required, and any mismatch results in a maximal shift. */
  241. period = MAX (suffix, needle_len - suffix) + 1;
  242. j = 0;
  243. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  244. {
  245. /* Scan for matches in right half. */
  246. i = suffix;
  247. while (i < needle_len && (CANON_ELEMENT (needle[i])
  248. == CANON_ELEMENT (haystack[i + j])))
  249. ++i;
  250. if (needle_len <= i)
  251. {
  252. /* Scan for matches in left half. */
  253. i = suffix - 1;
  254. while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
  255. == CANON_ELEMENT (haystack[i + j])))
  256. --i;
  257. if (i == SIZE_MAX)
  258. return (RETURN_TYPE) (haystack + j);
  259. j += period;
  260. }
  261. else
  262. j += i - suffix + 1;
  263. }
  264. }
  265. return NULL;
  266. }
  267. /* Return the first location of non-empty NEEDLE within HAYSTACK, or
  268. NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
  269. method is optimized for LONG_NEEDLE_THRESHOLD <= NEEDLE_LEN.
  270. Performance is guaranteed to be linear, with an initialization cost
  271. of 3 * NEEDLE_LEN + (1 << CHAR_BIT) operations.
  272. If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
  273. most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching,
  274. and sublinear performance O(HAYSTACK_LEN / NEEDLE_LEN) is possible.
  275. If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
  276. HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching, and
  277. sublinear performance is not possible. */
  278. static RETURN_TYPE
  279. two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
  280. const unsigned char *needle, size_t needle_len)
  281. {
  282. size_t i; /* Index into current byte of NEEDLE. */
  283. size_t j; /* Index into current window of HAYSTACK. */
  284. size_t period; /* The period of the right half of needle. */
  285. size_t suffix; /* The index of the right half of needle. */
  286. size_t shift_table[1U << CHAR_BIT]; /* See below. */
  287. /* Factor the needle into two halves, such that the left half is
  288. smaller than the global period, and the right half is
  289. periodic (with a period as large as NEEDLE_LEN - suffix). */
  290. suffix = critical_factorization (needle, needle_len, &period);
  291. /* Populate shift_table. For each possible byte value c,
  292. shift_table[c] is the distance from the last occurrence of c to
  293. the end of NEEDLE, or NEEDLE_LEN if c is absent from the NEEDLE.
  294. shift_table[NEEDLE[NEEDLE_LEN - 1]] contains the only 0. */
  295. for (i = 0; i < 1U << CHAR_BIT; i++)
  296. shift_table[i] = needle_len;
  297. for (i = 0; i < needle_len; i++)
  298. shift_table[CANON_ELEMENT (needle[i])] = needle_len - i - 1;
  299. /* Perform the search. Each iteration compares the right half
  300. first. */
  301. if (CMP_FUNC (needle, needle + period, suffix) == 0)
  302. {
  303. /* Entire needle is periodic; a mismatch can only advance by the
  304. period, so use memory to avoid rescanning known occurrences
  305. of the period. */
  306. size_t memory = 0;
  307. size_t shift;
  308. j = 0;
  309. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  310. {
  311. /* Check the last byte first; if it does not match, then
  312. shift to the next possible match location. */
  313. shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
  314. if (0 < shift)
  315. {
  316. if (memory && shift < period)
  317. {
  318. /* Since needle is periodic, but the last period has
  319. a byte out of place, there can be no match until
  320. after the mismatch. */
  321. shift = needle_len - period;
  322. memory = 0;
  323. }
  324. j += shift;
  325. continue;
  326. }
  327. /* Scan for matches in right half. The last byte has
  328. already been matched, by virtue of the shift table. */
  329. i = MAX (suffix, memory);
  330. while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
  331. == CANON_ELEMENT (haystack[i + j])))
  332. ++i;
  333. if (needle_len - 1 <= i)
  334. {
  335. /* Scan for matches in left half. */
  336. i = suffix - 1;
  337. while (memory < i + 1 && (CANON_ELEMENT (needle[i])
  338. == CANON_ELEMENT (haystack[i + j])))
  339. --i;
  340. if (i + 1 < memory + 1)
  341. return (RETURN_TYPE) (haystack + j);
  342. /* No match, so remember how many repetitions of period
  343. on the right half were scanned. */
  344. j += period;
  345. memory = needle_len - period;
  346. }
  347. else
  348. {
  349. j += i - suffix + 1;
  350. memory = 0;
  351. }
  352. }
  353. }
  354. else
  355. {
  356. /* The two halves of needle are distinct; no extra memory is
  357. required, and any mismatch results in a maximal shift. */
  358. size_t shift;
  359. period = MAX (suffix, needle_len - suffix) + 1;
  360. j = 0;
  361. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  362. {
  363. /* Check the last byte first; if it does not match, then
  364. shift to the next possible match location. */
  365. shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
  366. if (0 < shift)
  367. {
  368. j += shift;
  369. continue;
  370. }
  371. /* Scan for matches in right half. The last byte has
  372. already been matched, by virtue of the shift table. */
  373. i = suffix;
  374. while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
  375. == CANON_ELEMENT (haystack[i + j])))
  376. ++i;
  377. if (needle_len - 1 <= i)
  378. {
  379. /* Scan for matches in left half. */
  380. i = suffix - 1;
  381. while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
  382. == CANON_ELEMENT (haystack[i + j])))
  383. --i;
  384. if (i == SIZE_MAX)
  385. return (RETURN_TYPE) (haystack + j);
  386. j += period;
  387. }
  388. else
  389. j += i - suffix + 1;
  390. }
  391. }
  392. return NULL;
  393. }
  394. #undef AVAILABLE
  395. #undef CANON_ELEMENT
  396. #undef CMP_FUNC
  397. #undef MAX
  398. #undef RETURN_TYPE