str-two-way.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. /* Byte-wise substring search, using the Two-Way algorithm.
  2. Copyright (C) 2008-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Written by Eric Blake <ebb9@byu.net>, 2008.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library 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 GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, see
  15. <http://www.gnu.org/licenses/>. */
  16. /* Before including this file, you need to include <string.h> (and
  17. <config.h> before that, if not part of libc), and define:
  18. RETURN_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. Other macros you may optionally define:
  35. RET0_IF_0(a) Documented below at default definition.
  36. CHECK_EOL Same.
  37. This file undefines the macros listed above, and defines
  38. LONG_NEEDLE_THRESHOLD.
  39. */
  40. #include <limits.h>
  41. #include <stdint.h>
  42. #include <sys/param.h> /* Defines MAX. */
  43. /* We use the Two-Way string matching algorithm, which guarantees
  44. linear complexity with constant space. Additionally, for long
  45. needles, we also use a bad character shift table similar to the
  46. Boyer-Moore algorithm to achieve improved (potentially sub-linear)
  47. performance.
  48. See http://www-igm.univ-mlv.fr/~lecroq/string/node26.html#SECTION00260
  49. and http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm
  50. */
  51. /* Point at which computing a bad-byte shift table is likely to be
  52. worthwhile. Small needles should not compute a table, since it
  53. adds (1 << CHAR_BIT) + NEEDLE_LEN computations of preparation for a
  54. speedup no greater than a factor of NEEDLE_LEN. The larger the
  55. needle, the better the potential performance gain. On the other
  56. hand, on non-POSIX systems with CHAR_BIT larger than eight, the
  57. memory required for the table is prohibitive. */
  58. #if CHAR_BIT < 10
  59. # define LONG_NEEDLE_THRESHOLD 32U
  60. #else
  61. # define LONG_NEEDLE_THRESHOLD SIZE_MAX
  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. /* Check for end-of-line in strstr and strcasestr routines.
  70. We piggy-back matching procedure for detecting EOL where possible,
  71. and use AVAILABLE macro otherwise. */
  72. #ifndef CHECK_EOL
  73. # define CHECK_EOL (0)
  74. #endif
  75. /* Return NULL if argument is '\0'. */
  76. #ifndef RET0_IF_0
  77. # define RET0_IF_0(a) /* nothing */
  78. #endif
  79. /* Perform a critical factorization of NEEDLE, of length NEEDLE_LEN.
  80. Return the index of the first byte in the right half, and set
  81. *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).
  85. When NEEDLE is factored into two halves, a local period is the
  86. length of the smallest word that shares a suffix with the left half
  87. and shares a prefix with the right half. All factorizations of a
  88. non-empty NEEDLE have a local period of at least 1 and no greater
  89. than NEEDLE_LEN.
  90. A critical factorization has the property that the local period
  91. equals the global period. All strings have at least one critical
  92. factorization with the left half smaller than the global period.
  93. Given an ordered alphabet, a critical factorization can be computed
  94. in linear time, with 2 * NEEDLE_LEN comparisons, by computing the
  95. larger of two ordered maximal suffixes. The ordered maximal
  96. suffixes are determined by lexicographic comparison of
  97. periodicity. */
  98. static size_t
  99. critical_factorization (const unsigned char *needle, size_t needle_len,
  100. size_t *period)
  101. {
  102. /* Index of last byte of left half, or SIZE_MAX. */
  103. size_t max_suffix, max_suffix_rev;
  104. size_t j; /* Index into NEEDLE for current candidate suffix. */
  105. size_t k; /* Offset into current period. */
  106. size_t p; /* Intermediate period. */
  107. unsigned char a, b; /* Current comparison bytes. */
  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 longer suffix. Return the first byte of the right
  184. half, rather than the last byte of the left half. */
  185. if (max_suffix_rev + 1 < max_suffix + 1)
  186. return max_suffix + 1;
  187. *period = p;
  188. return max_suffix_rev + 1;
  189. }
  190. /* Return the first location of non-empty NEEDLE within HAYSTACK, or
  191. NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
  192. method is optimized for NEEDLE_LEN < LONG_NEEDLE_THRESHOLD.
  193. Performance is guaranteed to be linear, with an initialization cost
  194. of 2 * NEEDLE_LEN comparisons.
  195. If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
  196. most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.
  197. If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
  198. HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. */
  199. static RETURN_TYPE
  200. two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
  201. const unsigned char *needle, size_t needle_len)
  202. {
  203. size_t i; /* Index into current byte of NEEDLE. */
  204. size_t j; /* Index into current window of HAYSTACK. */
  205. size_t period; /* The period of the right half of needle. */
  206. size_t suffix; /* The index of the right half of needle. */
  207. /* Factor the needle into two halves, such that the left half is
  208. smaller than the global period, and the right half is
  209. periodic (with a period as large as NEEDLE_LEN - suffix). */
  210. suffix = critical_factorization (needle, needle_len, &period);
  211. /* Perform the search. Each iteration compares the right half
  212. first. */
  213. if (CMP_FUNC (needle, needle + period, suffix) == 0)
  214. {
  215. /* Entire needle is periodic; a mismatch can only advance by the
  216. period, so use memory to avoid rescanning known occurrences
  217. of the period. */
  218. size_t memory = 0;
  219. j = 0;
  220. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  221. {
  222. const unsigned char *pneedle;
  223. const unsigned char *phaystack;
  224. /* Scan for matches in right half. */
  225. i = MAX (suffix, memory);
  226. pneedle = &needle[i];
  227. phaystack = &haystack[i + j];
  228. while (i < needle_len && (CANON_ELEMENT (*pneedle++)
  229. == CANON_ELEMENT (*phaystack++)))
  230. ++i;
  231. if (needle_len <= i)
  232. {
  233. /* Scan for matches in left half. */
  234. i = suffix - 1;
  235. pneedle = &needle[i];
  236. phaystack = &haystack[i + j];
  237. while (memory < i + 1 && (CANON_ELEMENT (*pneedle--)
  238. == CANON_ELEMENT (*phaystack--)))
  239. --i;
  240. if (i + 1 < memory + 1)
  241. return (RETURN_TYPE) (haystack + j);
  242. /* No match, so remember how many repetitions of period
  243. on the right half were scanned. */
  244. j += period;
  245. memory = needle_len - period;
  246. }
  247. else
  248. {
  249. j += i - suffix + 1;
  250. memory = 0;
  251. }
  252. }
  253. }
  254. else
  255. {
  256. const unsigned char *phaystack;
  257. /* The comparison always starts from needle[suffix], so cache it
  258. and use an optimized first-character loop. */
  259. unsigned char needle_suffix = CANON_ELEMENT (needle[suffix]);
  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. unsigned char haystack_char;
  267. const unsigned char *pneedle;
  268. phaystack = &haystack[suffix + j];
  269. #ifdef FASTSEARCH
  270. if (*phaystack++ != needle_suffix)
  271. {
  272. phaystack = FASTSEARCH (phaystack, needle_suffix,
  273. haystack_len - needle_len - j);
  274. if (phaystack == NULL)
  275. goto ret0;
  276. j = phaystack - &haystack[suffix];
  277. phaystack++;
  278. }
  279. #else
  280. while (needle_suffix
  281. != (haystack_char = CANON_ELEMENT (*phaystack++)))
  282. {
  283. RET0_IF_0 (haystack_char);
  284. # if !CHECK_EOL
  285. ++j;
  286. if (!AVAILABLE (haystack, haystack_len, j, needle_len))
  287. goto ret0;
  288. # endif
  289. }
  290. # if CHECK_EOL
  291. /* Calculate J if it wasn't kept up-to-date in the first-character
  292. loop. */
  293. j = phaystack - &haystack[suffix] - 1;
  294. # endif
  295. #endif
  296. /* Scan for matches in right half. */
  297. i = suffix + 1;
  298. pneedle = &needle[i];
  299. while (i < needle_len)
  300. {
  301. if (CANON_ELEMENT (*pneedle++)
  302. != (haystack_char = CANON_ELEMENT (*phaystack++)))
  303. {
  304. RET0_IF_0 (haystack_char);
  305. break;
  306. }
  307. ++i;
  308. }
  309. #if CHECK_EOL
  310. /* Update minimal length of haystack. */
  311. if (phaystack > haystack + haystack_len)
  312. haystack_len = phaystack - haystack;
  313. #endif
  314. if (needle_len <= i)
  315. {
  316. /* Scan for matches in left half. */
  317. i = suffix - 1;
  318. pneedle = &needle[i];
  319. phaystack = &haystack[i + j];
  320. while (i != SIZE_MAX)
  321. {
  322. if (CANON_ELEMENT (*pneedle--)
  323. != (haystack_char = CANON_ELEMENT (*phaystack--)))
  324. {
  325. RET0_IF_0 (haystack_char);
  326. break;
  327. }
  328. --i;
  329. }
  330. if (i == SIZE_MAX)
  331. return (RETURN_TYPE) (haystack + j);
  332. j += period;
  333. }
  334. else
  335. j += i - suffix + 1;
  336. }
  337. }
  338. ret0: __attribute__ ((unused))
  339. return NULL;
  340. }
  341. /* Return the first location of non-empty NEEDLE within HAYSTACK, or
  342. NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
  343. method is optimized for LONG_NEEDLE_THRESHOLD <= NEEDLE_LEN.
  344. Performance is guaranteed to be linear, with an initialization cost
  345. of 3 * NEEDLE_LEN + (1 << CHAR_BIT) operations.
  346. If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
  347. most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching,
  348. and sublinear performance O(HAYSTACK_LEN / NEEDLE_LEN) is possible.
  349. If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
  350. HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching, and
  351. sublinear performance is not possible. */
  352. static RETURN_TYPE
  353. two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
  354. const unsigned char *needle, size_t needle_len)
  355. {
  356. size_t i; /* Index into current byte of NEEDLE. */
  357. size_t j; /* Index into current window of HAYSTACK. */
  358. size_t period; /* The period of the right half of needle. */
  359. size_t suffix; /* The index of the right half of needle. */
  360. size_t shift_table[1U << CHAR_BIT]; /* See below. */
  361. /* Factor the needle into two halves, such that the left half is
  362. smaller than the global period, and the right half is
  363. periodic (with a period as large as NEEDLE_LEN - suffix). */
  364. suffix = critical_factorization (needle, needle_len, &period);
  365. /* Populate shift_table. For each possible byte value c,
  366. shift_table[c] is the distance from the last occurrence of c to
  367. the end of NEEDLE, or NEEDLE_LEN if c is absent from the NEEDLE.
  368. shift_table[NEEDLE[NEEDLE_LEN - 1]] contains the only 0. */
  369. for (i = 0; i < 1U << CHAR_BIT; i++)
  370. shift_table[i] = needle_len;
  371. for (i = 0; i < needle_len; i++)
  372. shift_table[CANON_ELEMENT (needle[i])] = needle_len - i - 1;
  373. /* Perform the search. Each iteration compares the right half
  374. first. */
  375. if (CMP_FUNC (needle, needle + period, suffix) == 0)
  376. {
  377. /* Entire needle is periodic; a mismatch can only advance by the
  378. period, so use memory to avoid rescanning known occurrences
  379. of the period. */
  380. size_t memory = 0;
  381. size_t shift;
  382. j = 0;
  383. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  384. {
  385. const unsigned char *pneedle;
  386. const unsigned char *phaystack;
  387. /* Check the last byte first; if it does not match, then
  388. shift to the next possible match location. */
  389. shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
  390. if (0 < shift)
  391. {
  392. if (memory && shift < period)
  393. {
  394. /* Since needle is periodic, but the last period has
  395. a byte out of place, there can be no match until
  396. after the mismatch. */
  397. shift = needle_len - period;
  398. }
  399. memory = 0;
  400. j += shift;
  401. continue;
  402. }
  403. /* Scan for matches in right half. The last byte has
  404. already been matched, by virtue of the shift table. */
  405. i = MAX (suffix, memory);
  406. pneedle = &needle[i];
  407. phaystack = &haystack[i + j];
  408. while (i < needle_len - 1 && (CANON_ELEMENT (*pneedle++)
  409. == CANON_ELEMENT (*phaystack++)))
  410. ++i;
  411. if (needle_len - 1 <= i)
  412. {
  413. /* Scan for matches in left half. */
  414. i = suffix - 1;
  415. pneedle = &needle[i];
  416. phaystack = &haystack[i + j];
  417. while (memory < i + 1 && (CANON_ELEMENT (*pneedle--)
  418. == CANON_ELEMENT (*phaystack--)))
  419. --i;
  420. if (i + 1 < memory + 1)
  421. return (RETURN_TYPE) (haystack + j);
  422. /* No match, so remember how many repetitions of period
  423. on the right half were scanned. */
  424. j += period;
  425. memory = needle_len - period;
  426. }
  427. else
  428. {
  429. j += i - suffix + 1;
  430. memory = 0;
  431. }
  432. }
  433. }
  434. else
  435. {
  436. /* The two halves of needle are distinct; no extra memory is
  437. required, and any mismatch results in a maximal shift. */
  438. size_t shift;
  439. period = MAX (suffix, needle_len - suffix) + 1;
  440. j = 0;
  441. while (AVAILABLE (haystack, haystack_len, j, needle_len))
  442. {
  443. const unsigned char *pneedle;
  444. const unsigned char *phaystack;
  445. /* Check the last byte first; if it does not match, then
  446. shift to the next possible match location. */
  447. shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
  448. if (0 < shift)
  449. {
  450. j += shift;
  451. continue;
  452. }
  453. /* Scan for matches in right half. The last byte has
  454. already been matched, by virtue of the shift table. */
  455. i = suffix;
  456. pneedle = &needle[i];
  457. phaystack = &haystack[i + j];
  458. while (i < needle_len - 1 && (CANON_ELEMENT (*pneedle++)
  459. == CANON_ELEMENT (*phaystack++)))
  460. ++i;
  461. if (needle_len - 1 <= i)
  462. {
  463. /* Scan for matches in left half. */
  464. i = suffix - 1;
  465. pneedle = &needle[i];
  466. phaystack = &haystack[i + j];
  467. while (i != SIZE_MAX && (CANON_ELEMENT (*pneedle--)
  468. == CANON_ELEMENT (*phaystack--)))
  469. --i;
  470. if (i == SIZE_MAX)
  471. return (RETURN_TYPE) (haystack + j);
  472. j += period;
  473. }
  474. else
  475. j += i - suffix + 1;
  476. }
  477. }
  478. return NULL;
  479. }
  480. #undef AVAILABLE
  481. #undef CANON_ELEMENT
  482. #undef CMP_FUNC
  483. #undef RET0_IF_0
  484. #undef RETURN_TYPE
  485. #undef CHECK_EOL