mbsstr.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. /* Searching in a string. -*- coding: utf-8 -*-
  2. Copyright (C) 2005-2017 Free Software Foundation, Inc.
  3. Written by Bruno Haible <bruno@clisp.org>, 2005.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include <string.h>
  17. #include <stdbool.h>
  18. #include <stddef.h> /* for NULL, in case a nonstandard string.h lacks it */
  19. #include "malloca.h"
  20. #include "mbuiter.h"
  21. /* Knuth-Morris-Pratt algorithm. */
  22. #define UNIT unsigned char
  23. #define CANON_ELEMENT(c) c
  24. #include "str-kmp.h"
  25. /* Knuth-Morris-Pratt algorithm.
  26. See http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm
  27. Return a boolean indicating success:
  28. Return true and set *RESULTP if the search was completed.
  29. Return false if it was aborted because not enough memory was available. */
  30. static bool
  31. knuth_morris_pratt_multibyte (const char *haystack, const char *needle,
  32. const char **resultp)
  33. {
  34. size_t m = mbslen (needle);
  35. mbchar_t *needle_mbchars;
  36. size_t *table;
  37. /* Allocate room for needle_mbchars and the table. */
  38. void *memory = nmalloca (m, sizeof (mbchar_t) + sizeof (size_t));
  39. void *table_memory;
  40. if (memory == NULL)
  41. return false;
  42. needle_mbchars = memory;
  43. table_memory = needle_mbchars + m;
  44. table = table_memory;
  45. /* Fill needle_mbchars. */
  46. {
  47. mbui_iterator_t iter;
  48. size_t j;
  49. j = 0;
  50. for (mbui_init (iter, needle); mbui_avail (iter); mbui_advance (iter), j++)
  51. mb_copy (&needle_mbchars[j], &mbui_cur (iter));
  52. }
  53. /* Fill the table.
  54. For 0 < i < m:
  55. 0 < table[i] <= i is defined such that
  56. forall 0 < x < table[i]: needle[x..i-1] != needle[0..i-1-x],
  57. and table[i] is as large as possible with this property.
  58. This implies:
  59. 1) For 0 < i < m:
  60. If table[i] < i,
  61. needle[table[i]..i-1] = needle[0..i-1-table[i]].
  62. 2) For 0 < i < m:
  63. rhaystack[0..i-1] == needle[0..i-1]
  64. and exists h, i <= h < m: rhaystack[h] != needle[h]
  65. implies
  66. forall 0 <= x < table[i]: rhaystack[x..x+m-1] != needle[0..m-1].
  67. table[0] remains uninitialized. */
  68. {
  69. size_t i, j;
  70. /* i = 1: Nothing to verify for x = 0. */
  71. table[1] = 1;
  72. j = 0;
  73. for (i = 2; i < m; i++)
  74. {
  75. /* Here: j = i-1 - table[i-1].
  76. The inequality needle[x..i-1] != needle[0..i-1-x] is known to hold
  77. for x < table[i-1], by induction.
  78. Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1]. */
  79. mbchar_t *b = &needle_mbchars[i - 1];
  80. for (;;)
  81. {
  82. /* Invariants: The inequality needle[x..i-1] != needle[0..i-1-x]
  83. is known to hold for x < i-1-j.
  84. Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1]. */
  85. if (mb_equal (*b, needle_mbchars[j]))
  86. {
  87. /* Set table[i] := i-1-j. */
  88. table[i] = i - ++j;
  89. break;
  90. }
  91. /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
  92. for x = i-1-j, because
  93. needle[i-1] != needle[j] = needle[i-1-x]. */
  94. if (j == 0)
  95. {
  96. /* The inequality holds for all possible x. */
  97. table[i] = i;
  98. break;
  99. }
  100. /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
  101. for i-1-j < x < i-1-j+table[j], because for these x:
  102. needle[x..i-2]
  103. = needle[x-(i-1-j)..j-1]
  104. != needle[0..j-1-(x-(i-1-j))] (by definition of table[j])
  105. = needle[0..i-2-x],
  106. hence needle[x..i-1] != needle[0..i-1-x].
  107. Furthermore
  108. needle[i-1-j+table[j]..i-2]
  109. = needle[table[j]..j-1]
  110. = needle[0..j-1-table[j]] (by definition of table[j]). */
  111. j = j - table[j];
  112. }
  113. /* Here: j = i - table[i]. */
  114. }
  115. }
  116. /* Search, using the table to accelerate the processing. */
  117. {
  118. size_t j;
  119. mbui_iterator_t rhaystack;
  120. mbui_iterator_t phaystack;
  121. *resultp = NULL;
  122. j = 0;
  123. mbui_init (rhaystack, haystack);
  124. mbui_init (phaystack, haystack);
  125. /* Invariant: phaystack = rhaystack + j. */
  126. while (mbui_avail (phaystack))
  127. if (mb_equal (needle_mbchars[j], mbui_cur (phaystack)))
  128. {
  129. j++;
  130. mbui_advance (phaystack);
  131. if (j == m)
  132. {
  133. /* The entire needle has been found. */
  134. *resultp = mbui_cur_ptr (rhaystack);
  135. break;
  136. }
  137. }
  138. else if (j > 0)
  139. {
  140. /* Found a match of needle[0..j-1], mismatch at needle[j]. */
  141. size_t count = table[j];
  142. j -= count;
  143. for (; count > 0; count--)
  144. {
  145. if (!mbui_avail (rhaystack))
  146. abort ();
  147. mbui_advance (rhaystack);
  148. }
  149. }
  150. else
  151. {
  152. /* Found a mismatch at needle[0] already. */
  153. if (!mbui_avail (rhaystack))
  154. abort ();
  155. mbui_advance (rhaystack);
  156. mbui_advance (phaystack);
  157. }
  158. }
  159. freea (memory);
  160. return true;
  161. }
  162. /* Find the first occurrence of the character string NEEDLE in the character
  163. string HAYSTACK. Return NULL if NEEDLE is not found in HAYSTACK. */
  164. char *
  165. mbsstr (const char *haystack, const char *needle)
  166. {
  167. /* Be careful not to look at the entire extent of haystack or needle
  168. until needed. This is useful because of these two cases:
  169. - haystack may be very long, and a match of needle found early,
  170. - needle may be very long, and not even a short initial segment of
  171. needle may be found in haystack. */
  172. if (MB_CUR_MAX > 1)
  173. {
  174. mbui_iterator_t iter_needle;
  175. mbui_init (iter_needle, needle);
  176. if (mbui_avail (iter_needle))
  177. {
  178. /* Minimizing the worst-case complexity:
  179. Let n = mbslen(haystack), m = mbslen(needle).
  180. The naïve algorithm is O(n*m) worst-case.
  181. The Knuth-Morris-Pratt algorithm is O(n) worst-case but it needs a
  182. memory allocation.
  183. To achieve linear complexity and yet amortize the cost of the
  184. memory allocation, we activate the Knuth-Morris-Pratt algorithm
  185. only once the naïve algorithm has already run for some time; more
  186. precisely, when
  187. - the outer loop count is >= 10,
  188. - the average number of comparisons per outer loop is >= 5,
  189. - the total number of comparisons is >= m.
  190. But we try it only once. If the memory allocation attempt failed,
  191. we don't retry it. */
  192. bool try_kmp = true;
  193. size_t outer_loop_count = 0;
  194. size_t comparison_count = 0;
  195. size_t last_ccount = 0; /* last comparison count */
  196. mbui_iterator_t iter_needle_last_ccount; /* = needle + last_ccount */
  197. mbui_iterator_t iter_haystack;
  198. mbui_init (iter_needle_last_ccount, needle);
  199. mbui_init (iter_haystack, haystack);
  200. for (;; mbui_advance (iter_haystack))
  201. {
  202. if (!mbui_avail (iter_haystack))
  203. /* No match. */
  204. return NULL;
  205. /* See whether it's advisable to use an asymptotically faster
  206. algorithm. */
  207. if (try_kmp
  208. && outer_loop_count >= 10
  209. && comparison_count >= 5 * outer_loop_count)
  210. {
  211. /* See if needle + comparison_count now reaches the end of
  212. needle. */
  213. size_t count = comparison_count - last_ccount;
  214. for (;
  215. count > 0 && mbui_avail (iter_needle_last_ccount);
  216. count--)
  217. mbui_advance (iter_needle_last_ccount);
  218. last_ccount = comparison_count;
  219. if (!mbui_avail (iter_needle_last_ccount))
  220. {
  221. /* Try the Knuth-Morris-Pratt algorithm. */
  222. const char *result;
  223. bool success =
  224. knuth_morris_pratt_multibyte (haystack, needle,
  225. &result);
  226. if (success)
  227. return (char *) result;
  228. try_kmp = false;
  229. }
  230. }
  231. outer_loop_count++;
  232. comparison_count++;
  233. if (mb_equal (mbui_cur (iter_haystack), mbui_cur (iter_needle)))
  234. /* The first character matches. */
  235. {
  236. mbui_iterator_t rhaystack;
  237. mbui_iterator_t rneedle;
  238. memcpy (&rhaystack, &iter_haystack, sizeof (mbui_iterator_t));
  239. mbui_advance (rhaystack);
  240. mbui_init (rneedle, needle);
  241. if (!mbui_avail (rneedle))
  242. abort ();
  243. mbui_advance (rneedle);
  244. for (;; mbui_advance (rhaystack), mbui_advance (rneedle))
  245. {
  246. if (!mbui_avail (rneedle))
  247. /* Found a match. */
  248. return (char *) mbui_cur_ptr (iter_haystack);
  249. if (!mbui_avail (rhaystack))
  250. /* No match. */
  251. return NULL;
  252. comparison_count++;
  253. if (!mb_equal (mbui_cur (rhaystack), mbui_cur (rneedle)))
  254. /* Nothing in this round. */
  255. break;
  256. }
  257. }
  258. }
  259. }
  260. else
  261. return (char *) haystack;
  262. }
  263. else
  264. {
  265. if (*needle != '\0')
  266. {
  267. /* Minimizing the worst-case complexity:
  268. Let n = strlen(haystack), m = strlen(needle).
  269. The naïve algorithm is O(n*m) worst-case.
  270. The Knuth-Morris-Pratt algorithm is O(n) worst-case but it needs a
  271. memory allocation.
  272. To achieve linear complexity and yet amortize the cost of the
  273. memory allocation, we activate the Knuth-Morris-Pratt algorithm
  274. only once the naïve algorithm has already run for some time; more
  275. precisely, when
  276. - the outer loop count is >= 10,
  277. - the average number of comparisons per outer loop is >= 5,
  278. - the total number of comparisons is >= m.
  279. But we try it only once. If the memory allocation attempt failed,
  280. we don't retry it. */
  281. bool try_kmp = true;
  282. size_t outer_loop_count = 0;
  283. size_t comparison_count = 0;
  284. size_t last_ccount = 0; /* last comparison count */
  285. const char *needle_last_ccount = needle; /* = needle + last_ccount */
  286. /* Speed up the following searches of needle by caching its first
  287. character. */
  288. char b = *needle++;
  289. for (;; haystack++)
  290. {
  291. if (*haystack == '\0')
  292. /* No match. */
  293. return NULL;
  294. /* See whether it's advisable to use an asymptotically faster
  295. algorithm. */
  296. if (try_kmp
  297. && outer_loop_count >= 10
  298. && comparison_count >= 5 * outer_loop_count)
  299. {
  300. /* See if needle + comparison_count now reaches the end of
  301. needle. */
  302. if (needle_last_ccount != NULL)
  303. {
  304. needle_last_ccount +=
  305. strnlen (needle_last_ccount,
  306. comparison_count - last_ccount);
  307. if (*needle_last_ccount == '\0')
  308. needle_last_ccount = NULL;
  309. last_ccount = comparison_count;
  310. }
  311. if (needle_last_ccount == NULL)
  312. {
  313. /* Try the Knuth-Morris-Pratt algorithm. */
  314. const unsigned char *result;
  315. bool success =
  316. knuth_morris_pratt ((const unsigned char *) haystack,
  317. (const unsigned char *) (needle - 1),
  318. strlen (needle - 1),
  319. &result);
  320. if (success)
  321. return (char *) result;
  322. try_kmp = false;
  323. }
  324. }
  325. outer_loop_count++;
  326. comparison_count++;
  327. if (*haystack == b)
  328. /* The first character matches. */
  329. {
  330. const char *rhaystack = haystack + 1;
  331. const char *rneedle = needle;
  332. for (;; rhaystack++, rneedle++)
  333. {
  334. if (*rneedle == '\0')
  335. /* Found a match. */
  336. return (char *) haystack;
  337. if (*rhaystack == '\0')
  338. /* No match. */
  339. return NULL;
  340. comparison_count++;
  341. if (*rhaystack != *rneedle)
  342. /* Nothing in this round. */
  343. break;
  344. }
  345. }
  346. }
  347. }
  348. else
  349. return (char *) haystack;
  350. }
  351. }