str-two-way.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /* Byte-wise substring search, using the Two-Way algorithm.
  2. Copyright (C) 2008-2013 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, see <http://www.gnu.org/licenses/>. */
  15. /* Before including this file, you need to include <config.h> and
  16. <string.h>, and define:
  17. RESULT_TYPE A macro that expands to the return type.
  18. AVAILABLE(h, h_l, j, n_l)
  19. A macro that returns nonzero if there are
  20. at least N_L bytes left starting at H[J].
  21. H is 'unsigned char *', H_L, J, and N_L
  22. are 'size_t'; H_L is an lvalue. For
  23. NUL-terminated searches, H_L can be
  24. modified each iteration to avoid having
  25. to compute the end of H up front.
  26. For case-insensitivity, you may optionally define:
  27. CMP_FUNC(p1, p2, l) A macro that returns 0 iff the first L
  28. characters of P1 and P2 are equal.
  29. CANON_ELEMENT(c) A macro that canonicalizes an element right after
  30. it has been fetched from one of the two strings.
  31. The argument is an 'unsigned char'; the result
  32. must be an 'unsigned char' as well.
  33. This file undefines the macros documented above, and defines
  34. LONG_NEEDLE_THRESHOLD.
  35. */
  36. #include <limits.h>
  37. #include <stdint.h>
  38. /* We use the Two-Way string matching algorithm (also known as
  39. Chrochemore-Perrin), which guarantees linear complexity with
  40. constant space. Additionally, for long needles, we also use a bad
  41. character shift table similar to the Boyer-Moore algorithm to
  42. achieve improved (potentially sub-linear) performance.
  43. See http://www-igm.univ-mlv.fr/~lecroq/string/node26.html#SECTION00260,
  44. http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm,
  45. http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.34.6641&rep=rep1&type=pdf
  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, or SIZE_MAX. */
  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. 0 <= j < NEEDLE_LEN - 1
  109. -1 <= max_suffix{,_rev} < j (treating SIZE_MAX as if it were signed)
  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 = SIZE_MAX;
  117. j = 0;
  118. k = p = 1;
  119. while (j + k < needle_len)
  120. {
  121. a = CANON_ELEMENT (needle[j + k]);
  122. b = CANON_ELEMENT (needle[max_suffix + k]);
  123. if (a < b)
  124. {
  125. /* Suffix is smaller, period is entire prefix so far. */
  126. j += k;
  127. k = 1;
  128. p = j - max_suffix;
  129. }
  130. else if (a == b)
  131. {
  132. /* Advance through repetition of the current period. */
  133. if (k != p)
  134. ++k;
  135. else
  136. {
  137. j += p;
  138. k = 1;
  139. }
  140. }
  141. else /* b < a */
  142. {
  143. /* Suffix is larger, start over from current location. */
  144. max_suffix = j++;
  145. k = p = 1;
  146. }
  147. }
  148. *period = p;
  149. /* Perform reverse lexicographic search. */
  150. max_suffix_rev = SIZE_MAX;
  151. j = 0;
  152. k = p = 1;
  153. while (j + k < needle_len)
  154. {
  155. a = CANON_ELEMENT (needle[j + k]);
  156. b = CANON_ELEMENT (needle[max_suffix_rev + k]);
  157. if (b < a)
  158. {
  159. /* Suffix is smaller, period is entire prefix so far. */
  160. j += k;
  161. k = 1;
  162. p = j - max_suffix_rev;
  163. }
  164. else if (a == b)
  165. {
  166. /* Advance through repetition of the current period. */
  167. if (k != p)
  168. ++k;
  169. else
  170. {
  171. j += p;
  172. k = 1;
  173. }
  174. }
  175. else /* a < b */
  176. {
  177. /* Suffix is larger, start over from current location. */
  178. max_suffix_rev = j++;
  179. k = p = 1;
  180. }
  181. }
  182. /* Choose the shorter suffix. Return the index of the first byte of
  183. the right half, rather than the last byte of the left half.
  184. For some examples, 'banana' has two critical factorizations, both
  185. exposed by the two lexicographic extreme suffixes of 'anana' and
  186. 'nana', where both suffixes have a period of 2. On the other
  187. hand, with 'aab' and 'bba', both strings have a single critical
  188. factorization of the last byte, with the suffix having a period
  189. of 1. While the maximal lexicographic suffix of 'aab' is 'b',
  190. the maximal lexicographic suffix of 'bba' is 'ba', which is not a
  191. critical factorization. Conversely, the maximal reverse
  192. lexicographic suffix of 'a' works for 'bba', but not 'ab' for
  193. 'aab'. The shorter suffix of the two will always be a critical
  194. factorization. */
  195. if (max_suffix_rev + 1 < max_suffix + 1)
  196. return max_suffix + 1;
  197. *period = p;
  198. return max_suffix_rev + 1;
  199. }
  200. /* Return the first location of non-empty NEEDLE within HAYSTACK, or
  201. NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
  202. method is optimized for NEEDLE_LEN < LONG_NEEDLE_THRESHOLD.
  203. Performance is guaranteed to be linear, with an initialization cost
  204. of 2 * NEEDLE_LEN comparisons.
  205. If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
  206. most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.
  207. If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
  208. HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. */
  209. static RETURN_TYPE
  210. two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
  211. const unsigned char *needle, size_t needle_len)
  212. {
  213. size_t i; /* Index into current byte of NEEDLE. */
  214. size_t j; /* Index into current window of HAYSTACK. */
  215. size_t period; /* The period of the right half of needle. */
  216. 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);
  221. /* Perform the search. Each iteration compares the right half
  222. first. */
  223. if (CMP_FUNC (needle, needle + period, suffix) == 0)
  224. {
  225. /* Entire needle is periodic; a mismatch in the left half can
  226. only advance by the period, so use memory to avoid rescanning
  227. known occurrences of the period in the right half. */
  228. size_t memory = 0;
  229. j = 0;
  230. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  231. {
  232. /* Scan for matches in right half. */
  233. i = MAX (suffix, memory);
  234. while (i < needle_len && (CANON_ELEMENT (needle[i])
  235. == CANON_ELEMENT (haystack[i + j])))
  236. ++i;
  237. if (needle_len <= i)
  238. {
  239. /* Scan for matches in left half. */
  240. i = suffix - 1;
  241. while (memory < i + 1 && (CANON_ELEMENT (needle[i])
  242. == CANON_ELEMENT (haystack[i + j])))
  243. --i;
  244. if (i + 1 < memory + 1)
  245. return (RETURN_TYPE) (haystack + j);
  246. /* No match, so remember how many repetitions of period
  247. on the right half were scanned. */
  248. j += period;
  249. memory = needle_len - period;
  250. }
  251. else
  252. {
  253. j += i - suffix + 1;
  254. memory = 0;
  255. }
  256. }
  257. }
  258. else
  259. {
  260. /* The two halves of needle are distinct; no extra memory is
  261. required, and any mismatch results in a maximal shift. */
  262. period = MAX (suffix, needle_len - suffix) + 1;
  263. j = 0;
  264. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  265. {
  266. /* Scan for matches in right half. */
  267. i = suffix;
  268. while (i < needle_len && (CANON_ELEMENT (needle[i])
  269. == CANON_ELEMENT (haystack[i + j])))
  270. ++i;
  271. if (needle_len <= i)
  272. {
  273. /* Scan for matches in left half. */
  274. i = suffix - 1;
  275. while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
  276. == CANON_ELEMENT (haystack[i + j])))
  277. --i;
  278. if (i == SIZE_MAX)
  279. return (RETURN_TYPE) (haystack + j);
  280. j += period;
  281. }
  282. else
  283. j += i - suffix + 1;
  284. }
  285. }
  286. return NULL;
  287. }
  288. /* Return the first location of non-empty NEEDLE within HAYSTACK, or
  289. NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
  290. method is optimized for LONG_NEEDLE_THRESHOLD <= NEEDLE_LEN.
  291. Performance is guaranteed to be linear, with an initialization cost
  292. of 3 * NEEDLE_LEN + (1 << CHAR_BIT) operations.
  293. If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
  294. most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching,
  295. and sublinear performance O(HAYSTACK_LEN / NEEDLE_LEN) is possible.
  296. If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
  297. HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching, and
  298. sublinear performance is not possible. */
  299. static RETURN_TYPE
  300. two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
  301. const unsigned char *needle, size_t needle_len)
  302. {
  303. size_t i; /* Index into current byte of NEEDLE. */
  304. size_t j; /* Index into current window of HAYSTACK. */
  305. size_t period; /* The period of the right half of needle. */
  306. size_t suffix; /* The index of the right half of needle. */
  307. size_t shift_table[1U << CHAR_BIT]; /* See below. */
  308. /* Factor the needle into two halves, such that the left half is
  309. smaller than the global period, and the right half is
  310. periodic (with a period as large as NEEDLE_LEN - suffix). */
  311. suffix = critical_factorization (needle, needle_len, &period);
  312. /* Populate shift_table. For each possible byte value c,
  313. shift_table[c] is the distance from the last occurrence of c to
  314. the end of NEEDLE, or NEEDLE_LEN if c is absent from the NEEDLE.
  315. shift_table[NEEDLE[NEEDLE_LEN - 1]] contains the only 0. */
  316. for (i = 0; i < 1U << CHAR_BIT; i++)
  317. shift_table[i] = needle_len;
  318. for (i = 0; i < needle_len; i++)
  319. shift_table[CANON_ELEMENT (needle[i])] = needle_len - i - 1;
  320. /* Perform the search. Each iteration compares the right half
  321. first. */
  322. if (CMP_FUNC (needle, needle + period, suffix) == 0)
  323. {
  324. /* Entire needle is periodic; a mismatch in the left half can
  325. only advance by the period, so use memory to avoid rescanning
  326. known occurrences of the period in the right half. */
  327. size_t memory = 0;
  328. size_t shift;
  329. j = 0;
  330. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  331. {
  332. /* Check the last byte first; if it does not match, then
  333. shift to the next possible match location. */
  334. shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
  335. if (0 < shift)
  336. {
  337. if (memory && shift < period)
  338. {
  339. /* Since needle is periodic, but the last period has
  340. a byte out of place, there can be no match until
  341. after the mismatch. */
  342. shift = needle_len - period;
  343. }
  344. memory = 0;
  345. j += shift;
  346. continue;
  347. }
  348. /* Scan for matches in right half. The last byte has
  349. already been matched, by virtue of the shift table. */
  350. i = MAX (suffix, memory);
  351. while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
  352. == CANON_ELEMENT (haystack[i + j])))
  353. ++i;
  354. if (needle_len - 1 <= i)
  355. {
  356. /* Scan for matches in left half. */
  357. i = suffix - 1;
  358. while (memory < i + 1 && (CANON_ELEMENT (needle[i])
  359. == CANON_ELEMENT (haystack[i + j])))
  360. --i;
  361. if (i + 1 < memory + 1)
  362. return (RETURN_TYPE) (haystack + j);
  363. /* No match, so remember how many repetitions of period
  364. on the right half were scanned. */
  365. j += period;
  366. memory = needle_len - period;
  367. }
  368. else
  369. {
  370. j += i - suffix + 1;
  371. memory = 0;
  372. }
  373. }
  374. }
  375. else
  376. {
  377. /* The two halves of needle are distinct; no extra memory is
  378. required, and any mismatch results in a maximal shift. */
  379. size_t shift;
  380. period = MAX (suffix, needle_len - suffix) + 1;
  381. j = 0;
  382. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  383. {
  384. /* Check the last byte first; if it does not match, then
  385. shift to the next possible match location. */
  386. shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
  387. if (0 < shift)
  388. {
  389. j += shift;
  390. continue;
  391. }
  392. /* Scan for matches in right half. The last byte has
  393. already been matched, by virtue of the shift table. */
  394. i = suffix;
  395. while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
  396. == CANON_ELEMENT (haystack[i + j])))
  397. ++i;
  398. if (needle_len - 1 <= i)
  399. {
  400. /* Scan for matches in left half. */
  401. i = suffix - 1;
  402. while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
  403. == CANON_ELEMENT (haystack[i + j])))
  404. --i;
  405. if (i == SIZE_MAX)
  406. return (RETURN_TYPE) (haystack + j);
  407. j += period;
  408. }
  409. else
  410. j += i - suffix + 1;
  411. }
  412. }
  413. return NULL;
  414. }
  415. #undef AVAILABLE
  416. #undef CANON_ELEMENT
  417. #undef CMP_FUNC
  418. #undef MAX
  419. #undef RETURN_TYPE