- /* Be careful not to look at the entire extent of haystack or needle
- until needed. This is useful because of these two cases:
- - haystack may be very long, and a match of needle found early,
- - needle may be very long, and not even a short initial segment of
- needle may be found in haystack. */
-#if HAVE_MBRTOWC
- if (MB_CUR_MAX > 1)
- {
- mbui_iterator_t iter_needle;
-
- mbui_init (iter_needle, needle);
- if (mbui_avail (iter_needle))
- {
- mbchar_t b;
- mbui_iterator_t iter_haystack;
-
- mb_copy (&b, &mbui_cur (iter_needle));
- if (b.wc_valid)
- b.wc = towlower (b.wc);
-
- mbui_init (iter_haystack, haystack);
- for (;; mbui_advance (iter_haystack))
- {
- mbchar_t c;
-
- if (!mbui_avail (iter_haystack))
- /* No match. */
- return NULL;
-
- mb_copy (&c, &mbui_cur (iter_haystack));
- if (c.wc_valid)
- c.wc = towlower (c.wc);
- if (mb_equal (c, b))
- /* The first character matches. */
- {
- mbui_iterator_t rhaystack;
- mbui_iterator_t rneedle;
-
- memcpy (&rhaystack, &iter_haystack, sizeof (mbui_iterator_t));
- mbui_advance (rhaystack);
-
- mbui_init (rneedle, needle);
- if (!mbui_avail (rneedle))
- abort ();
- mbui_advance (rneedle);
-
- for (;; mbui_advance (rhaystack), mbui_advance (rneedle))
- {
- if (!mbui_avail (rneedle))
- /* Found a match. */
- return (char *) mbui_cur_ptr (iter_haystack);
- if (!mbui_avail (rhaystack))
- /* No match. */
- return NULL;
- if (!mb_caseequal (mbui_cur (rhaystack),
- mbui_cur (rneedle)))
- /* Nothing in this round. */
- break;
- }
- }
- }
- }
- else
- return (char *) haystack;
- }
- else
-#endif
+ const char *haystack = haystack_start;
+ const char *needle = needle_start;
+ size_t needle_len; /* Length of NEEDLE. */
+ size_t haystack_len; /* Known minimum length of HAYSTACK. */
+ bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
+
+ /* Determine length of NEEDLE, and in the process, make sure
+ HAYSTACK is at least as long (no point processing all of a long
+ NEEDLE if HAYSTACK is too short). */
+ while (*haystack && *needle)