str-two-way.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. /* Byte-wise substring search, using the Two-Way algorithm.
  2. Copyright (C) 2008-2011 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 (also known as
  40. Chrochemore-Perrin), which guarantees linear complexity with
  41. constant space. Additionally, for long needles, we also use a bad
  42. character shift table similar to the Boyer-Moore algorithm to
  43. achieve improved (potentially sub-linear) performance.
  44. See http://www-igm.univ-mlv.fr/~lecroq/string/node26.html#SECTION00260,
  45. http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm,
  46. http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.34.6641&rep=rep1&type=pdf
  47. */
  48. /* Point at which computing a bad-byte shift table is likely to be
  49. worthwhile. Small needles should not compute a table, since it
  50. adds (1 << CHAR_BIT) + NEEDLE_LEN computations of preparation for a
  51. speedup no greater than a factor of NEEDLE_LEN. The larger the
  52. needle, the better the potential performance gain. On the other
  53. hand, on non-POSIX systems with CHAR_BIT larger than eight, the
  54. memory required for the table is prohibitive. */
  55. #if CHAR_BIT < 10
  56. # define LONG_NEEDLE_THRESHOLD 32U
  57. #else
  58. # define LONG_NEEDLE_THRESHOLD SIZE_MAX
  59. #endif
  60. #ifndef MAX
  61. # define MAX(a, b) ((a < b) ? (b) : (a))
  62. #endif
  63. #ifndef CANON_ELEMENT
  64. # define CANON_ELEMENT(c) c
  65. #endif
  66. #ifndef CMP_FUNC
  67. # define CMP_FUNC memcmp
  68. #endif
  69. /* Perform a critical factorization of NEEDLE, of length NEEDLE_LEN.
  70. Return the index of the first byte in the right half, and set
  71. *PERIOD to the global period of the right half.
  72. The global period of a string is the smallest index (possibly its
  73. length) at which all remaining bytes in the string are repetitions
  74. of the prefix (the last repetition may be a subset of the prefix).
  75. When NEEDLE is factored into two halves, a local period is the
  76. length of the smallest word that shares a suffix with the left half
  77. and shares a prefix with the right half. All factorizations of a
  78. non-empty NEEDLE have a local period of at least 1 and no greater
  79. than NEEDLE_LEN.
  80. A critical factorization has the property that the local period
  81. equals the global period. All strings have at least one critical
  82. factorization with the left half smaller than the global period.
  83. And while some strings have more than one critical factorization,
  84. it is provable that with an ordered alphabet, at least one of the
  85. critical factorizations corresponds to a maximal suffix.
  86. Given an ordered alphabet, a critical factorization can be computed
  87. in linear time, with 2 * NEEDLE_LEN comparisons, by computing the
  88. shorter of two ordered maximal suffixes. The ordered maximal
  89. suffixes are determined by lexicographic comparison while tracking
  90. periodicity. */
  91. static size_t
  92. critical_factorization (const unsigned char *needle, size_t needle_len,
  93. size_t *period)
  94. {
  95. /* Index of last byte of left half, or SIZE_MAX. */
  96. size_t max_suffix, max_suffix_rev;
  97. size_t j; /* Index into NEEDLE for current candidate suffix. */
  98. size_t k; /* Offset into current period. */
  99. size_t p; /* Intermediate period. */
  100. unsigned char a, b; /* Current comparison bytes. */
  101. /* Special case NEEDLE_LEN of 1 or 2 (all callers already filtered
  102. out 0-length needles. */
  103. if (needle_len < 3)
  104. {
  105. *period = 1;
  106. return needle_len - 1;
  107. }
  108. /* Invariants:
  109. 0 <= j < NEEDLE_LEN - 1
  110. -1 <= max_suffix{,_rev} < j (treating SIZE_MAX as if it were signed)
  111. min(max_suffix, max_suffix_rev) < global period of NEEDLE
  112. 1 <= p <= global period of NEEDLE
  113. p == global period of the substring NEEDLE[max_suffix{,_rev}+1...j]
  114. 1 <= k <= p
  115. */
  116. /* Perform lexicographic search. */
  117. max_suffix = SIZE_MAX;
  118. j = 0;
  119. k = p = 1;
  120. while (j + k < needle_len)
  121. {
  122. a = CANON_ELEMENT (needle[j + k]);
  123. b = CANON_ELEMENT (needle[max_suffix + k]);
  124. if (a < b)
  125. {
  126. /* Suffix is smaller, period is entire prefix so far. */
  127. j += k;
  128. k = 1;
  129. p = j - max_suffix;
  130. }
  131. else if (a == b)
  132. {
  133. /* Advance through repetition of the current period. */
  134. if (k != p)
  135. ++k;
  136. else
  137. {
  138. j += p;
  139. k = 1;
  140. }
  141. }
  142. else /* b < a */
  143. {
  144. /* Suffix is larger, start over from current location. */
  145. max_suffix = j++;
  146. k = p = 1;
  147. }
  148. }
  149. *period = p;
  150. /* Perform reverse lexicographic search. */
  151. max_suffix_rev = SIZE_MAX;
  152. j = 0;
  153. k = p = 1;
  154. while (j + k < needle_len)
  155. {
  156. a = CANON_ELEMENT (needle[j + k]);
  157. b = CANON_ELEMENT (needle[max_suffix_rev + k]);
  158. if (b < a)
  159. {
  160. /* Suffix is smaller, period is entire prefix so far. */
  161. j += k;
  162. k = 1;
  163. p = j - max_suffix_rev;
  164. }
  165. else if (a == b)
  166. {
  167. /* Advance through repetition of the current period. */
  168. if (k != p)
  169. ++k;
  170. else
  171. {
  172. j += p;
  173. k = 1;
  174. }
  175. }
  176. else /* a < b */
  177. {
  178. /* Suffix is larger, start over from current location. */
  179. max_suffix_rev = j++;
  180. k = p = 1;
  181. }
  182. }
  183. /* Choose the shorter suffix. Return the index of the first byte of
  184. the right half, rather than the last byte of the left half.
  185. For some examples, 'banana' has two critical factorizations, both
  186. exposed by the two lexicographic extreme suffixes of 'anana' and
  187. 'nana', where both suffixes have a period of 2. On the other
  188. hand, with 'aab' and 'bba', both strings have a single critical
  189. factorization of the last byte, with the suffix having a period
  190. of 1. While the maximal lexicographic suffix of 'aab' is 'b',
  191. the maximal lexicographic suffix of 'bba' is 'ba', which is not a
  192. critical factorization. Conversely, the maximal reverse
  193. lexicographic suffix of 'a' works for 'bba', but not 'ab' for
  194. 'aab'. The shorter suffix of the two will always be a critical
  195. factorization. */
  196. if (max_suffix_rev + 1 < max_suffix + 1)
  197. return max_suffix + 1;
  198. *period = p;
  199. return max_suffix_rev + 1;
  200. }
  201. /* Return the first location of non-empty NEEDLE within HAYSTACK, or
  202. NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
  203. method is optimized for NEEDLE_LEN < LONG_NEEDLE_THRESHOLD.
  204. Performance is guaranteed to be linear, with an initialization cost
  205. of 2 * NEEDLE_LEN comparisons.
  206. If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
  207. most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.
  208. If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
  209. HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. */
  210. static RETURN_TYPE
  211. two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
  212. const unsigned char *needle, size_t needle_len)
  213. {
  214. size_t i; /* Index into current byte of NEEDLE. */
  215. size_t j; /* Index into current window of HAYSTACK. */
  216. size_t period; /* The period of the right half of needle. */
  217. size_t suffix; /* The index of the right half of needle. */
  218. /* Factor the needle into two halves, such that the left half is
  219. smaller than the global period, and the right half is
  220. periodic (with a period as large as NEEDLE_LEN - suffix). */
  221. suffix = critical_factorization (needle, needle_len, &period);
  222. /* Perform the search. Each iteration compares the right half
  223. first. */
  224. if (CMP_FUNC (needle, needle + period, suffix) == 0)
  225. {
  226. /* Entire needle is periodic; a mismatch in the left half can
  227. only advance by the period, so use memory to avoid rescanning
  228. known occurrences of the period in the right half. */
  229. size_t memory = 0;
  230. j = 0;
  231. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  232. {
  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])))
  237. ++i;
  238. if (needle_len <= i)
  239. {
  240. /* Scan for matches in left half. */
  241. i = suffix - 1;
  242. while (memory < i + 1 && (CANON_ELEMENT (needle[i])
  243. == CANON_ELEMENT (haystack[i + j])))
  244. --i;
  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. */
  249. j += period;
  250. memory = needle_len - period;
  251. }
  252. else
  253. {
  254. j += i - suffix + 1;
  255. memory = 0;
  256. }
  257. }
  258. }
  259. else
  260. {
  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;
  264. j = 0;
  265. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  266. {
  267. /* Scan for matches in right half. */
  268. i = suffix;
  269. while (i < needle_len && (CANON_ELEMENT (needle[i])
  270. == CANON_ELEMENT (haystack[i + j])))
  271. ++i;
  272. if (needle_len <= i)
  273. {
  274. /* Scan for matches in left half. */
  275. i = suffix - 1;
  276. while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
  277. == CANON_ELEMENT (haystack[i + j])))
  278. --i;
  279. if (i == SIZE_MAX)
  280. return (RETURN_TYPE) (haystack + j);
  281. j += period;
  282. }
  283. else
  284. j += i - suffix + 1;
  285. }
  286. }
  287. return NULL;
  288. }
  289. /* Return the first location of non-empty NEEDLE within HAYSTACK, or
  290. NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
  291. method is optimized for LONG_NEEDLE_THRESHOLD <= NEEDLE_LEN.
  292. Performance is guaranteed to be linear, with an initialization cost
  293. of 3 * NEEDLE_LEN + (1 << CHAR_BIT) operations.
  294. If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
  295. most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching,
  296. and sublinear performance O(HAYSTACK_LEN / NEEDLE_LEN) is possible.
  297. If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
  298. HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching, and
  299. sublinear performance is not possible. */
  300. static RETURN_TYPE
  301. two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
  302. const unsigned char *needle, size_t needle_len)
  303. {
  304. size_t i; /* Index into current byte of NEEDLE. */
  305. size_t j; /* Index into current window of HAYSTACK. */
  306. size_t period; /* The period of the right half of needle. */
  307. size_t suffix; /* The index of the right half of needle. */
  308. size_t shift_table[1U << CHAR_BIT]; /* See below. */
  309. /* Factor the needle into two halves, such that the left half is
  310. smaller than the global period, and the right half is
  311. periodic (with a period as large as NEEDLE_LEN - suffix). */
  312. suffix = critical_factorization (needle, needle_len, &period);
  313. /* Populate shift_table. For each possible byte value c,
  314. shift_table[c] is the distance from the last occurrence of c to
  315. the end of NEEDLE, or NEEDLE_LEN if c is absent from the NEEDLE.
  316. shift_table[NEEDLE[NEEDLE_LEN - 1]] contains the only 0. */
  317. for (i = 0; i < 1U << CHAR_BIT; i++)
  318. shift_table[i] = needle_len;
  319. for (i = 0; i < needle_len; i++)
  320. shift_table[CANON_ELEMENT (needle[i])] = needle_len - i - 1;
  321. /* Perform the search. Each iteration compares the right half
  322. first. */
  323. if (CMP_FUNC (needle, needle + period, suffix) == 0)
  324. {
  325. /* Entire needle is periodic; a mismatch in the left half can
  326. only advance by the period, so use memory to avoid rescanning
  327. known occurrences of the period in the right half. */
  328. size_t memory = 0;
  329. size_t shift;
  330. j = 0;
  331. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  332. {
  333. /* Check the last byte first; if it does not match, then
  334. shift to the next possible match location. */
  335. shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
  336. if (0 < shift)
  337. {
  338. if (memory && shift < period)
  339. {
  340. /* Since needle is periodic, but the last period has
  341. a byte out of place, there can be no match until
  342. after the mismatch. */
  343. shift = needle_len - period;
  344. }
  345. memory = 0;
  346. j += shift;
  347. continue;
  348. }
  349. /* Scan for matches in right half. The last byte has
  350. already been matched, by virtue of the shift table. */
  351. i = MAX (suffix, memory);
  352. while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
  353. == CANON_ELEMENT (haystack[i + j])))
  354. ++i;
  355. if (needle_len - 1 <= i)
  356. {
  357. /* Scan for matches in left half. */
  358. i = suffix - 1;
  359. while (memory < i + 1 && (CANON_ELEMENT (needle[i])
  360. == CANON_ELEMENT (haystack[i + j])))
  361. --i;
  362. if (i + 1 < memory + 1)
  363. return (RETURN_TYPE) (haystack + j);
  364. /* No match, so remember how many repetitions of period
  365. on the right half were scanned. */
  366. j += period;
  367. memory = needle_len - period;
  368. }
  369. else
  370. {
  371. j += i - suffix + 1;
  372. memory = 0;
  373. }
  374. }
  375. }
  376. else
  377. {
  378. /* The two halves of needle are distinct; no extra memory is
  379. required, and any mismatch results in a maximal shift. */
  380. size_t shift;
  381. period = MAX (suffix, needle_len - suffix) + 1;
  382. j = 0;
  383. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  384. {
  385. /* Check the last byte first; if it does not match, then
  386. shift to the next possible match location. */
  387. shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
  388. if (0 < shift)
  389. {
  390. j += shift;
  391. continue;
  392. }
  393. /* Scan for matches in right half. The last byte has
  394. already been matched, by virtue of the shift table. */
  395. i = suffix;
  396. while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
  397. == CANON_ELEMENT (haystack[i + j])))
  398. ++i;
  399. if (needle_len - 1 <= i)
  400. {
  401. /* Scan for matches in left half. */
  402. i = suffix - 1;
  403. while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
  404. == CANON_ELEMENT (haystack[i + j])))
  405. --i;
  406. if (i == SIZE_MAX)
  407. return (RETURN_TYPE) (haystack + j);
  408. j += period;
  409. }
  410. else
  411. j += i - suffix + 1;
  412. }
  413. }
  414. return NULL;
  415. }
  416. #undef AVAILABLE
  417. #undef CANON_ELEMENT
  418. #undef CMP_FUNC
  419. #undef MAX
  420. #undef RETURN_TYPE