1 /* Searching in a string.
2 Copyright (C) 2005 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2005.
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 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
30 /* Find the first occurrence of NEEDLE in HAYSTACK. */
32 strstr (const char *haystack, const char *needle)
34 /* Be careful not to look at the entire extent of haystack or needle
35 until needed. This is useful because of these two cases:
36 - haystack may be very long, and a match of needle found early,
37 - needle may be very long, and not even a short initial segment of
38 needle may be found in haystack. */
42 mbui_iterator_t iter_needle;
44 mbui_init (iter_needle, needle);
45 if (mbui_avail (iter_needle))
47 mbui_iterator_t iter_haystack;
49 mbui_init (iter_haystack, haystack);
50 for (;; mbui_advance (iter_haystack))
52 if (!mbui_avail (iter_haystack))
56 if (mb_equal (mbui_cur (iter_haystack), mbui_cur (iter_needle)))
57 /* The first character matches. */
59 mbui_iterator_t rhaystack;
60 mbui_iterator_t rneedle;
62 memcpy (&rhaystack, &iter_haystack, sizeof (mbui_iterator_t));
63 mbui_advance (rhaystack);
65 mbui_init (rneedle, needle);
66 if (!mbui_avail (rneedle))
68 mbui_advance (rneedle);
70 for (;; mbui_advance (rhaystack), mbui_advance (rneedle))
72 if (!mbui_avail (rneedle))
74 return (char *) haystack;
75 if (!mbui_avail (rhaystack))
78 if (!mb_equal (mbui_cur (rhaystack), mbui_cur (rneedle)))
79 /* Nothing in this round. */
86 return (char *) haystack;
93 /* Speed up the following searches of needle by caching its first
99 if (*haystack == '\0')
103 /* The first character matches. */
105 const char *rhaystack = haystack + 1;
106 const char *rneedle = needle;
108 for (;; rhaystack++, rneedle++)
110 if (*rneedle == '\0')
112 return (char *) haystack;
113 if (*rhaystack == '\0')
116 if (*rhaystack != *rneedle)
117 /* Nothing in this round. */
124 return (char *) haystack;