Rewrite c-strstr.c for maintainability.
[gnulib.git] / lib / c-strstr.c
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.
4
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)
8    any later version.
9
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.
14
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.  */
18
19 #include <config.h>
20
21 /* Specification.  */
22 #include "c-strstr.h"
23
24 #include <stddef.h>
25
26 /* Find the first occurrence of NEEDLE in HAYSTACK.  */
27 char *
28 c_strstr (const char *haystack, const char *needle)
29 {
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.  */
35   if (*needle != '\0')
36     {
37       /* Speed up the following searches of needle by caching its first
38          character.  */
39       unsigned char b = (unsigned char) *needle;
40
41       needle++;
42       for (;; haystack++)
43         {
44           if (*haystack == '\0')
45             /* No match.  */
46             return NULL;
47           if ((unsigned char) *haystack == b)
48             /* The first character matches.  */
49             {
50               const char *rhaystack = haystack + 1;
51               const char *rneedle = needle;
52
53               for (;; rhaystack++, rneedle++)
54                 {
55                   if (*rneedle == '\0')
56                     /* Found a match.  */
57                     return (char *) haystack;
58                   if (*rhaystack == '\0')
59                     /* No match.  */
60                     return NULL;
61                   if ((unsigned char) *rhaystack != (unsigned char) *rneedle)
62                     /* Nothing in this round.  */
63                     break;
64                 }
65             }
66         }
67     }
68   else
69     return (char *) haystack;
70 }