1 /* c-strstr.c -- substring search in C locale
2 Copyright (C) 2005-2007 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2005, 2007.
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. */
26 /* Find the first occurrence of NEEDLE in HAYSTACK. */
28 c_strstr (const char *haystack, const char *needle)
30 /* Be careful not to look at the entire extent of haystack or needle
31 until needed. This is useful because of these two cases:
32 - haystack may be very long, and a match of needle found early,
33 - needle may be very long, and not even a short initial segment of
34 needle may be found in haystack. */
37 /* Speed up the following searches of needle by caching its first
39 unsigned char b = (unsigned char) *needle;
44 if (*haystack == '\0')
47 if ((unsigned char) *haystack == b)
48 /* The first character matches. */
50 const char *rhaystack = haystack + 1;
51 const char *rneedle = needle;
53 for (;; rhaystack++, rneedle++)
57 return (char *) haystack;
58 if (*rhaystack == '\0')
61 if ((unsigned char) *rhaystack != (unsigned char) *rneedle)
62 /* Nothing in this round. */
69 return (char *) haystack;