fastsearch.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. /* stringlib: fastsearch implementation */
  2. #define STRINGLIB_FASTSEARCH_H
  3. /* fast search/count implementation, based on a mix between boyer-
  4. moore and horspool, with a few more bells and whistles on the top.
  5. for some more background, see:
  6. https://web.archive.org/web/20201107074620/http://effbot.org/zone/stringlib.htm */
  7. /* note: fastsearch may access s[n], which isn't a problem when using
  8. Python's ordinary string types, but may cause problems if you're
  9. using this code in other contexts. also, the count mode returns -1
  10. if there cannot possibly be a match in the target string, and 0 if
  11. it has actually checked for matches, but didn't find any. callers
  12. beware! */
  13. /* If the strings are long enough, use Crochemore and Perrin's Two-Way
  14. algorithm, which has worst-case O(n) runtime and best-case O(n/k).
  15. Also compute a table of shifts to achieve O(n/k) in more cases,
  16. and often (data dependent) deduce larger shifts than pure C&P can
  17. deduce. See stringlib_find_two_way_notes.txt in this folder for a
  18. detailed explanation. */
  19. #define FAST_COUNT 0
  20. #define FAST_SEARCH 1
  21. #define FAST_RSEARCH 2
  22. #if LONG_BIT >= 128
  23. #define STRINGLIB_BLOOM_WIDTH 128
  24. #elif LONG_BIT >= 64
  25. #define STRINGLIB_BLOOM_WIDTH 64
  26. #elif LONG_BIT >= 32
  27. #define STRINGLIB_BLOOM_WIDTH 32
  28. #else
  29. #error "LONG_BIT is smaller than 32"
  30. #endif
  31. #define STRINGLIB_BLOOM_ADD(mask, ch) \
  32. ((mask |= (1UL << ((ch) & (STRINGLIB_BLOOM_WIDTH -1)))))
  33. #define STRINGLIB_BLOOM(mask, ch) \
  34. ((mask & (1UL << ((ch) & (STRINGLIB_BLOOM_WIDTH -1)))))
  35. #ifdef STRINGLIB_FAST_MEMCHR
  36. # define MEMCHR_CUT_OFF 15
  37. #else
  38. # define MEMCHR_CUT_OFF 40
  39. #endif
  40. Py_LOCAL_INLINE(Py_ssize_t)
  41. STRINGLIB(find_char)(const STRINGLIB_CHAR* s, Py_ssize_t n, STRINGLIB_CHAR ch)
  42. {
  43. const STRINGLIB_CHAR *p, *e;
  44. p = s;
  45. e = s + n;
  46. if (n > MEMCHR_CUT_OFF) {
  47. #ifdef STRINGLIB_FAST_MEMCHR
  48. p = STRINGLIB_FAST_MEMCHR(s, ch, n);
  49. if (p != NULL)
  50. return (p - s);
  51. return -1;
  52. #else
  53. /* use memchr if we can choose a needle without too many likely
  54. false positives */
  55. const STRINGLIB_CHAR *s1, *e1;
  56. unsigned char needle = ch & 0xff;
  57. /* If looking for a multiple of 256, we'd have too
  58. many false positives looking for the '\0' byte in UCS2
  59. and UCS4 representations. */
  60. if (needle != 0) {
  61. do {
  62. void *candidate = memchr(p, needle,
  63. (e - p) * sizeof(STRINGLIB_CHAR));
  64. if (candidate == NULL)
  65. return -1;
  66. s1 = p;
  67. p = (const STRINGLIB_CHAR *)
  68. _Py_ALIGN_DOWN(candidate, sizeof(STRINGLIB_CHAR));
  69. if (*p == ch)
  70. return (p - s);
  71. /* False positive */
  72. p++;
  73. if (p - s1 > MEMCHR_CUT_OFF)
  74. continue;
  75. if (e - p <= MEMCHR_CUT_OFF)
  76. break;
  77. e1 = p + MEMCHR_CUT_OFF;
  78. while (p != e1) {
  79. if (*p == ch)
  80. return (p - s);
  81. p++;
  82. }
  83. }
  84. while (e - p > MEMCHR_CUT_OFF);
  85. }
  86. #endif
  87. }
  88. while (p < e) {
  89. if (*p == ch)
  90. return (p - s);
  91. p++;
  92. }
  93. return -1;
  94. }
  95. #undef MEMCHR_CUT_OFF
  96. #if STRINGLIB_SIZEOF_CHAR == 1
  97. # define MEMRCHR_CUT_OFF 15
  98. #else
  99. # define MEMRCHR_CUT_OFF 40
  100. #endif
  101. Py_LOCAL_INLINE(Py_ssize_t)
  102. STRINGLIB(rfind_char)(const STRINGLIB_CHAR* s, Py_ssize_t n, STRINGLIB_CHAR ch)
  103. {
  104. const STRINGLIB_CHAR *p;
  105. #ifdef HAVE_MEMRCHR
  106. /* memrchr() is a GNU extension, available since glibc 2.1.91. it
  107. doesn't seem as optimized as memchr(), but is still quite
  108. faster than our hand-written loop below. There is no wmemrchr
  109. for 4-byte chars. */
  110. if (n > MEMRCHR_CUT_OFF) {
  111. #if STRINGLIB_SIZEOF_CHAR == 1
  112. p = memrchr(s, ch, n);
  113. if (p != NULL)
  114. return (p - s);
  115. return -1;
  116. #else
  117. /* use memrchr if we can choose a needle without too many likely
  118. false positives */
  119. const STRINGLIB_CHAR *s1;
  120. Py_ssize_t n1;
  121. unsigned char needle = ch & 0xff;
  122. /* If looking for a multiple of 256, we'd have too
  123. many false positives looking for the '\0' byte in UCS2
  124. and UCS4 representations. */
  125. if (needle != 0) {
  126. do {
  127. void *candidate = memrchr(s, needle,
  128. n * sizeof(STRINGLIB_CHAR));
  129. if (candidate == NULL)
  130. return -1;
  131. n1 = n;
  132. p = (const STRINGLIB_CHAR *)
  133. _Py_ALIGN_DOWN(candidate, sizeof(STRINGLIB_CHAR));
  134. n = p - s;
  135. if (*p == ch)
  136. return n;
  137. /* False positive */
  138. if (n1 - n > MEMRCHR_CUT_OFF)
  139. continue;
  140. if (n <= MEMRCHR_CUT_OFF)
  141. break;
  142. s1 = p - MEMRCHR_CUT_OFF;
  143. while (p > s1) {
  144. p--;
  145. if (*p == ch)
  146. return (p - s);
  147. }
  148. n = p - s;
  149. }
  150. while (n > MEMRCHR_CUT_OFF);
  151. }
  152. #endif
  153. }
  154. #endif /* HAVE_MEMRCHR */
  155. p = s + n;
  156. while (p > s) {
  157. p--;
  158. if (*p == ch)
  159. return (p - s);
  160. }
  161. return -1;
  162. }
  163. #undef MEMRCHR_CUT_OFF
  164. /* Change to a 1 to see logging comments walk through the algorithm. */
  165. #if 0 && STRINGLIB_SIZEOF_CHAR == 1
  166. # define LOG(...) printf(__VA_ARGS__)
  167. # define LOG_STRING(s, n) printf("\"%.*s\"", (int)(n), s)
  168. # define LOG_LINEUP() do { \
  169. LOG("> "); LOG_STRING(haystack, len_haystack); LOG("\n> "); \
  170. LOG("%*s",(int)(window_last - haystack + 1 - len_needle), ""); \
  171. LOG_STRING(needle, len_needle); LOG("\n"); \
  172. } while(0)
  173. #else
  174. # define LOG(...)
  175. # define LOG_STRING(s, n)
  176. # define LOG_LINEUP()
  177. #endif
  178. Py_LOCAL_INLINE(Py_ssize_t)
  179. STRINGLIB(_lex_search)(const STRINGLIB_CHAR *needle, Py_ssize_t len_needle,
  180. Py_ssize_t *return_period, int invert_alphabet)
  181. {
  182. /* Do a lexicographic search. Essentially this:
  183. >>> max(needle[i:] for i in range(len(needle)+1))
  184. Also find the period of the right half. */
  185. Py_ssize_t max_suffix = 0;
  186. Py_ssize_t candidate = 1;
  187. Py_ssize_t k = 0;
  188. // The period of the right half.
  189. Py_ssize_t period = 1;
  190. while (candidate + k < len_needle) {
  191. // each loop increases candidate + k + max_suffix
  192. STRINGLIB_CHAR a = needle[candidate + k];
  193. STRINGLIB_CHAR b = needle[max_suffix + k];
  194. // check if the suffix at candidate is better than max_suffix
  195. if (invert_alphabet ? (b < a) : (a < b)) {
  196. // Fell short of max_suffix.
  197. // The next k + 1 characters are non-increasing
  198. // from candidate, so they won't start a maximal suffix.
  199. candidate += k + 1;
  200. k = 0;
  201. // We've ruled out any period smaller than what's
  202. // been scanned since max_suffix.
  203. period = candidate - max_suffix;
  204. }
  205. else if (a == b) {
  206. if (k + 1 != period) {
  207. // Keep scanning the equal strings
  208. k++;
  209. }
  210. else {
  211. // Matched a whole period.
  212. // Start matching the next period.
  213. candidate += period;
  214. k = 0;
  215. }
  216. }
  217. else {
  218. // Did better than max_suffix, so replace it.
  219. max_suffix = candidate;
  220. candidate++;
  221. k = 0;
  222. period = 1;
  223. }
  224. }
  225. *return_period = period;
  226. return max_suffix;
  227. }
  228. Py_LOCAL_INLINE(Py_ssize_t)
  229. STRINGLIB(_factorize)(const STRINGLIB_CHAR *needle,
  230. Py_ssize_t len_needle,
  231. Py_ssize_t *return_period)
  232. {
  233. /* Do a "critical factorization", making it so that:
  234. >>> needle = (left := needle[:cut]) + (right := needle[cut:])
  235. where the "local period" of the cut is maximal.
  236. The local period of the cut is the minimal length of a string w
  237. such that (left endswith w or w endswith left)
  238. and (right startswith w or w startswith left).
  239. The Critical Factorization Theorem says that this maximal local
  240. period is the global period of the string.
  241. Crochemore and Perrin (1991) show that this cut can be computed
  242. as the later of two cuts: one that gives a lexicographically
  243. maximal right half, and one that gives the same with the
  244. with respect to a reversed alphabet-ordering.
  245. This is what we want to happen:
  246. >>> x = "GCAGAGAG"
  247. >>> cut, period = factorize(x)
  248. >>> x[:cut], (right := x[cut:])
  249. ('GC', 'AGAGAG')
  250. >>> period # right half period
  251. 2
  252. >>> right[period:] == right[:-period]
  253. True
  254. This is how the local period lines up in the above example:
  255. GC | AGAGAG
  256. AGAGAGC = AGAGAGC
  257. The length of this minimal repetition is 7, which is indeed the
  258. period of the original string. */
  259. Py_ssize_t cut1, period1, cut2, period2, cut, period;
  260. cut1 = STRINGLIB(_lex_search)(needle, len_needle, &period1, 0);
  261. cut2 = STRINGLIB(_lex_search)(needle, len_needle, &period2, 1);
  262. // Take the later cut.
  263. if (cut1 > cut2) {
  264. period = period1;
  265. cut = cut1;
  266. }
  267. else {
  268. period = period2;
  269. cut = cut2;
  270. }
  271. LOG("split: "); LOG_STRING(needle, cut);
  272. LOG(" + "); LOG_STRING(needle + cut, len_needle - cut);
  273. LOG("\n");
  274. *return_period = period;
  275. return cut;
  276. }
  277. #define SHIFT_TYPE uint8_t
  278. #define MAX_SHIFT UINT8_MAX
  279. #define TABLE_SIZE_BITS 6u
  280. #define TABLE_SIZE (1U << TABLE_SIZE_BITS)
  281. #define TABLE_MASK (TABLE_SIZE - 1U)
  282. typedef struct STRINGLIB(_pre) {
  283. const STRINGLIB_CHAR *needle;
  284. Py_ssize_t len_needle;
  285. Py_ssize_t cut;
  286. Py_ssize_t period;
  287. Py_ssize_t gap;
  288. int is_periodic;
  289. SHIFT_TYPE table[TABLE_SIZE];
  290. } STRINGLIB(prework);
  291. static void
  292. STRINGLIB(_preprocess)(const STRINGLIB_CHAR *needle, Py_ssize_t len_needle,
  293. STRINGLIB(prework) *p)
  294. {
  295. p->needle = needle;
  296. p->len_needle = len_needle;
  297. p->cut = STRINGLIB(_factorize)(needle, len_needle, &(p->period));
  298. assert(p->period + p->cut <= len_needle);
  299. p->is_periodic = (0 == memcmp(needle,
  300. needle + p->period,
  301. p->cut * STRINGLIB_SIZEOF_CHAR));
  302. if (p->is_periodic) {
  303. assert(p->cut <= len_needle/2);
  304. assert(p->cut < p->period);
  305. p->gap = 0; // unused
  306. }
  307. else {
  308. // A lower bound on the period
  309. p->period = Py_MAX(p->cut, len_needle - p->cut) + 1;
  310. // The gap between the last character and the previous
  311. // occurrence of an equivalent character (modulo TABLE_SIZE)
  312. p->gap = len_needle;
  313. STRINGLIB_CHAR last = needle[len_needle - 1] & TABLE_MASK;
  314. for (Py_ssize_t i = len_needle - 2; i >= 0; i--) {
  315. STRINGLIB_CHAR x = needle[i] & TABLE_MASK;
  316. if (x == last) {
  317. p->gap = len_needle - 1 - i;
  318. break;
  319. }
  320. }
  321. }
  322. // Fill up a compressed Boyer-Moore "Bad Character" table
  323. Py_ssize_t not_found_shift = Py_MIN(len_needle, MAX_SHIFT);
  324. for (Py_ssize_t i = 0; i < (Py_ssize_t)TABLE_SIZE; i++) {
  325. p->table[i] = Py_SAFE_DOWNCAST(not_found_shift,
  326. Py_ssize_t, SHIFT_TYPE);
  327. }
  328. for (Py_ssize_t i = len_needle - not_found_shift; i < len_needle; i++) {
  329. SHIFT_TYPE shift = Py_SAFE_DOWNCAST(len_needle - 1 - i,
  330. Py_ssize_t, SHIFT_TYPE);
  331. p->table[needle[i] & TABLE_MASK] = shift;
  332. }
  333. }
  334. static Py_ssize_t
  335. STRINGLIB(_two_way)(const STRINGLIB_CHAR *haystack, Py_ssize_t len_haystack,
  336. STRINGLIB(prework) *p)
  337. {
  338. // Crochemore and Perrin's (1991) Two-Way algorithm.
  339. // See http://www-igm.univ-mlv.fr/~lecroq/string/node26.html#SECTION00260
  340. const Py_ssize_t len_needle = p->len_needle;
  341. const Py_ssize_t cut = p->cut;
  342. Py_ssize_t period = p->period;
  343. const STRINGLIB_CHAR *const needle = p->needle;
  344. const STRINGLIB_CHAR *window_last = haystack + len_needle - 1;
  345. const STRINGLIB_CHAR *const haystack_end = haystack + len_haystack;
  346. SHIFT_TYPE *table = p->table;
  347. const STRINGLIB_CHAR *window;
  348. LOG("===== Two-way: \"%s\" in \"%s\". =====\n", needle, haystack);
  349. if (p->is_periodic) {
  350. LOG("Needle is periodic.\n");
  351. Py_ssize_t memory = 0;
  352. periodicwindowloop:
  353. while (window_last < haystack_end) {
  354. assert(memory == 0);
  355. for (;;) {
  356. LOG_LINEUP();
  357. Py_ssize_t shift = table[(*window_last) & TABLE_MASK];
  358. window_last += shift;
  359. if (shift == 0) {
  360. break;
  361. }
  362. if (window_last >= haystack_end) {
  363. return -1;
  364. }
  365. LOG("Horspool skip\n");
  366. }
  367. no_shift:
  368. window = window_last - len_needle + 1;
  369. assert((window[len_needle - 1] & TABLE_MASK) ==
  370. (needle[len_needle - 1] & TABLE_MASK));
  371. Py_ssize_t i = Py_MAX(cut, memory);
  372. for (; i < len_needle; i++) {
  373. if (needle[i] != window[i]) {
  374. LOG("Right half does not match.\n");
  375. window_last += i - cut + 1;
  376. memory = 0;
  377. goto periodicwindowloop;
  378. }
  379. }
  380. for (i = memory; i < cut; i++) {
  381. if (needle[i] != window[i]) {
  382. LOG("Left half does not match.\n");
  383. window_last += period;
  384. memory = len_needle - period;
  385. if (window_last >= haystack_end) {
  386. return -1;
  387. }
  388. Py_ssize_t shift = table[(*window_last) & TABLE_MASK];
  389. if (shift) {
  390. // A mismatch has been identified to the right
  391. // of where i will next start, so we can jump
  392. // at least as far as if the mismatch occurred
  393. // on the first comparison.
  394. Py_ssize_t mem_jump = Py_MAX(cut, memory) - cut + 1;
  395. LOG("Skip with Memory.\n");
  396. memory = 0;
  397. window_last += Py_MAX(shift, mem_jump);
  398. goto periodicwindowloop;
  399. }
  400. goto no_shift;
  401. }
  402. }
  403. LOG("Found a match!\n");
  404. return window - haystack;
  405. }
  406. }
  407. else {
  408. Py_ssize_t gap = p->gap;
  409. period = Py_MAX(gap, period);
  410. LOG("Needle is not periodic.\n");
  411. Py_ssize_t gap_jump_end = Py_MIN(len_needle, cut + gap);
  412. windowloop:
  413. while (window_last < haystack_end) {
  414. for (;;) {
  415. LOG_LINEUP();
  416. Py_ssize_t shift = table[(*window_last) & TABLE_MASK];
  417. window_last += shift;
  418. if (shift == 0) {
  419. break;
  420. }
  421. if (window_last >= haystack_end) {
  422. return -1;
  423. }
  424. LOG("Horspool skip\n");
  425. }
  426. window = window_last - len_needle + 1;
  427. assert((window[len_needle - 1] & TABLE_MASK) ==
  428. (needle[len_needle - 1] & TABLE_MASK));
  429. for (Py_ssize_t i = cut; i < gap_jump_end; i++) {
  430. if (needle[i] != window[i]) {
  431. LOG("Early right half mismatch: jump by gap.\n");
  432. assert(gap >= i - cut + 1);
  433. window_last += gap;
  434. goto windowloop;
  435. }
  436. }
  437. for (Py_ssize_t i = gap_jump_end; i < len_needle; i++) {
  438. if (needle[i] != window[i]) {
  439. LOG("Late right half mismatch.\n");
  440. assert(i - cut + 1 > gap);
  441. window_last += i - cut + 1;
  442. goto windowloop;
  443. }
  444. }
  445. for (Py_ssize_t i = 0; i < cut; i++) {
  446. if (needle[i] != window[i]) {
  447. LOG("Left half does not match.\n");
  448. window_last += period;
  449. goto windowloop;
  450. }
  451. }
  452. LOG("Found a match!\n");
  453. return window - haystack;
  454. }
  455. }
  456. LOG("Not found. Returning -1.\n");
  457. return -1;
  458. }
  459. static Py_ssize_t
  460. STRINGLIB(_two_way_find)(const STRINGLIB_CHAR *haystack,
  461. Py_ssize_t len_haystack,
  462. const STRINGLIB_CHAR *needle,
  463. Py_ssize_t len_needle)
  464. {
  465. LOG("###### Finding \"%s\" in \"%s\".\n", needle, haystack);
  466. STRINGLIB(prework) p;
  467. STRINGLIB(_preprocess)(needle, len_needle, &p);
  468. return STRINGLIB(_two_way)(haystack, len_haystack, &p);
  469. }
  470. static Py_ssize_t
  471. STRINGLIB(_two_way_count)(const STRINGLIB_CHAR *haystack,
  472. Py_ssize_t len_haystack,
  473. const STRINGLIB_CHAR *needle,
  474. Py_ssize_t len_needle,
  475. Py_ssize_t maxcount)
  476. {
  477. LOG("###### Counting \"%s\" in \"%s\".\n", needle, haystack);
  478. STRINGLIB(prework) p;
  479. STRINGLIB(_preprocess)(needle, len_needle, &p);
  480. Py_ssize_t index = 0, count = 0;
  481. while (1) {
  482. Py_ssize_t result;
  483. result = STRINGLIB(_two_way)(haystack + index,
  484. len_haystack - index, &p);
  485. if (result == -1) {
  486. return count;
  487. }
  488. count++;
  489. if (count == maxcount) {
  490. return maxcount;
  491. }
  492. index += result + len_needle;
  493. }
  494. return count;
  495. }
  496. #undef SHIFT_TYPE
  497. #undef NOT_FOUND
  498. #undef SHIFT_OVERFLOW
  499. #undef TABLE_SIZE_BITS
  500. #undef TABLE_SIZE
  501. #undef TABLE_MASK
  502. #undef LOG
  503. #undef LOG_STRING
  504. #undef LOG_LINEUP
  505. static inline Py_ssize_t
  506. STRINGLIB(default_find)(const STRINGLIB_CHAR* s, Py_ssize_t n,
  507. const STRINGLIB_CHAR* p, Py_ssize_t m,
  508. Py_ssize_t maxcount, int mode)
  509. {
  510. const Py_ssize_t w = n - m;
  511. Py_ssize_t mlast = m - 1, count = 0;
  512. Py_ssize_t gap = mlast;
  513. const STRINGLIB_CHAR last = p[mlast];
  514. const STRINGLIB_CHAR *const ss = &s[mlast];
  515. unsigned long mask = 0;
  516. for (Py_ssize_t i = 0; i < mlast; i++) {
  517. STRINGLIB_BLOOM_ADD(mask, p[i]);
  518. if (p[i] == last) {
  519. gap = mlast - i - 1;
  520. }
  521. }
  522. STRINGLIB_BLOOM_ADD(mask, last);
  523. for (Py_ssize_t i = 0; i <= w; i++) {
  524. if (ss[i] == last) {
  525. /* candidate match */
  526. Py_ssize_t j;
  527. for (j = 0; j < mlast; j++) {
  528. if (s[i+j] != p[j]) {
  529. break;
  530. }
  531. }
  532. if (j == mlast) {
  533. /* got a match! */
  534. if (mode != FAST_COUNT) {
  535. return i;
  536. }
  537. count++;
  538. if (count == maxcount) {
  539. return maxcount;
  540. }
  541. i = i + mlast;
  542. continue;
  543. }
  544. /* miss: check if next character is part of pattern */
  545. if (!STRINGLIB_BLOOM(mask, ss[i+1])) {
  546. i = i + m;
  547. }
  548. else {
  549. i = i + gap;
  550. }
  551. }
  552. else {
  553. /* skip: check if next character is part of pattern */
  554. if (!STRINGLIB_BLOOM(mask, ss[i+1])) {
  555. i = i + m;
  556. }
  557. }
  558. }
  559. return mode == FAST_COUNT ? count : -1;
  560. }
  561. static Py_ssize_t
  562. STRINGLIB(adaptive_find)(const STRINGLIB_CHAR* s, Py_ssize_t n,
  563. const STRINGLIB_CHAR* p, Py_ssize_t m,
  564. Py_ssize_t maxcount, int mode)
  565. {
  566. const Py_ssize_t w = n - m;
  567. Py_ssize_t mlast = m - 1, count = 0;
  568. Py_ssize_t gap = mlast;
  569. Py_ssize_t hits = 0, res;
  570. const STRINGLIB_CHAR last = p[mlast];
  571. const STRINGLIB_CHAR *const ss = &s[mlast];
  572. unsigned long mask = 0;
  573. for (Py_ssize_t i = 0; i < mlast; i++) {
  574. STRINGLIB_BLOOM_ADD(mask, p[i]);
  575. if (p[i] == last) {
  576. gap = mlast - i - 1;
  577. }
  578. }
  579. STRINGLIB_BLOOM_ADD(mask, last);
  580. for (Py_ssize_t i = 0; i <= w; i++) {
  581. if (ss[i] == last) {
  582. /* candidate match */
  583. Py_ssize_t j;
  584. for (j = 0; j < mlast; j++) {
  585. if (s[i+j] != p[j]) {
  586. break;
  587. }
  588. }
  589. if (j == mlast) {
  590. /* got a match! */
  591. if (mode != FAST_COUNT) {
  592. return i;
  593. }
  594. count++;
  595. if (count == maxcount) {
  596. return maxcount;
  597. }
  598. i = i + mlast;
  599. continue;
  600. }
  601. hits += j + 1;
  602. if (hits > m / 4 && w - i > 2000) {
  603. if (mode == FAST_SEARCH) {
  604. res = STRINGLIB(_two_way_find)(s + i, n - i, p, m);
  605. return res == -1 ? -1 : res + i;
  606. }
  607. else {
  608. res = STRINGLIB(_two_way_count)(s + i, n - i, p, m,
  609. maxcount - count);
  610. return res + count;
  611. }
  612. }
  613. /* miss: check if next character is part of pattern */
  614. if (!STRINGLIB_BLOOM(mask, ss[i+1])) {
  615. i = i + m;
  616. }
  617. else {
  618. i = i + gap;
  619. }
  620. }
  621. else {
  622. /* skip: check if next character is part of pattern */
  623. if (!STRINGLIB_BLOOM(mask, ss[i+1])) {
  624. i = i + m;
  625. }
  626. }
  627. }
  628. return mode == FAST_COUNT ? count : -1;
  629. }
  630. static Py_ssize_t
  631. STRINGLIB(default_rfind)(const STRINGLIB_CHAR* s, Py_ssize_t n,
  632. const STRINGLIB_CHAR* p, Py_ssize_t m,
  633. Py_ssize_t maxcount, int mode)
  634. {
  635. /* create compressed boyer-moore delta 1 table */
  636. unsigned long mask = 0;
  637. Py_ssize_t i, j, mlast = m - 1, skip = m - 1, w = n - m;
  638. /* process pattern[0] outside the loop */
  639. STRINGLIB_BLOOM_ADD(mask, p[0]);
  640. /* process pattern[:0:-1] */
  641. for (i = mlast; i > 0; i--) {
  642. STRINGLIB_BLOOM_ADD(mask, p[i]);
  643. if (p[i] == p[0]) {
  644. skip = i - 1;
  645. }
  646. }
  647. for (i = w; i >= 0; i--) {
  648. if (s[i] == p[0]) {
  649. /* candidate match */
  650. for (j = mlast; j > 0; j--) {
  651. if (s[i+j] != p[j]) {
  652. break;
  653. }
  654. }
  655. if (j == 0) {
  656. /* got a match! */
  657. return i;
  658. }
  659. /* miss: check if previous character is part of pattern */
  660. if (i > 0 && !STRINGLIB_BLOOM(mask, s[i-1])) {
  661. i = i - m;
  662. }
  663. else {
  664. i = i - skip;
  665. }
  666. }
  667. else {
  668. /* skip: check if previous character is part of pattern */
  669. if (i > 0 && !STRINGLIB_BLOOM(mask, s[i-1])) {
  670. i = i - m;
  671. }
  672. }
  673. }
  674. return -1;
  675. }
  676. static inline Py_ssize_t
  677. STRINGLIB(count_char)(const STRINGLIB_CHAR *s, Py_ssize_t n,
  678. const STRINGLIB_CHAR p0, Py_ssize_t maxcount)
  679. {
  680. Py_ssize_t i, count = 0;
  681. for (i = 0; i < n; i++) {
  682. if (s[i] == p0) {
  683. count++;
  684. if (count == maxcount) {
  685. return maxcount;
  686. }
  687. }
  688. }
  689. return count;
  690. }
  691. Py_LOCAL_INLINE(Py_ssize_t)
  692. FASTSEARCH(const STRINGLIB_CHAR* s, Py_ssize_t n,
  693. const STRINGLIB_CHAR* p, Py_ssize_t m,
  694. Py_ssize_t maxcount, int mode)
  695. {
  696. if (n < m || (mode == FAST_COUNT && maxcount == 0)) {
  697. return -1;
  698. }
  699. /* look for special cases */
  700. if (m <= 1) {
  701. if (m <= 0) {
  702. return -1;
  703. }
  704. /* use special case for 1-character strings */
  705. if (mode == FAST_SEARCH)
  706. return STRINGLIB(find_char)(s, n, p[0]);
  707. else if (mode == FAST_RSEARCH)
  708. return STRINGLIB(rfind_char)(s, n, p[0]);
  709. else {
  710. return STRINGLIB(count_char)(s, n, p[0], maxcount);
  711. }
  712. }
  713. if (mode != FAST_RSEARCH) {
  714. if (n < 2500 || (m < 100 && n < 30000) || m < 6) {
  715. return STRINGLIB(default_find)(s, n, p, m, maxcount, mode);
  716. }
  717. else if ((m >> 2) * 3 < (n >> 2)) {
  718. /* 33% threshold, but don't overflow. */
  719. /* For larger problems where the needle isn't a huge
  720. percentage of the size of the haystack, the relatively
  721. expensive O(m) startup cost of the two-way algorithm
  722. will surely pay off. */
  723. if (mode == FAST_SEARCH) {
  724. return STRINGLIB(_two_way_find)(s, n, p, m);
  725. }
  726. else {
  727. return STRINGLIB(_two_way_count)(s, n, p, m, maxcount);
  728. }
  729. }
  730. else {
  731. /* To ensure that we have good worst-case behavior,
  732. here's an adaptive version of the algorithm, where if
  733. we match O(m) characters without any matches of the
  734. entire needle, then we predict that the startup cost of
  735. the two-way algorithm will probably be worth it. */
  736. return STRINGLIB(adaptive_find)(s, n, p, m, maxcount, mode);
  737. }
  738. }
  739. else {
  740. /* FAST_RSEARCH */
  741. return STRINGLIB(default_rfind)(s, n, p, m, maxcount, mode);
  742. }
  743. }