New module 'mbscasestr'. Reduced goal of 'strcasestr'.
[gnulib.git] / lib / strcasestr.c
1 /* Case-insensitive searching in a string.
2    Copyright (C) 2005-2007 Free Software Foundation, Inc.
3    Written by Bruno Haible <bruno@clisp.org>, 2005.
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 <string.h>
23
24 #include <ctype.h>
25 #include <stddef.h>  /* for NULL, in case a nonstandard string.h lacks it */
26
27 #define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch))
28
29 /* Find the first occurrence of NEEDLE in HAYSTACK, using case-insensitive
30    comparison.
31    Note: This function may, in multibyte locales, return success even if
32    strlen (haystack) < strlen (needle) !  */
33 char *
34 strcasestr (const char *haystack, const char *needle)
35 {
36   if (*needle != '\0')
37     {
38       /* Speed up the following searches of needle by caching its first
39          character.  */
40       unsigned char b = TOLOWER ((unsigned char) *needle);
41
42       needle++;
43       for (;; haystack++)
44         {
45           if (*haystack == '\0')
46             /* No match.  */
47             return NULL;
48           if (TOLOWER ((unsigned char) *haystack) == b)
49             /* The first character matches.  */
50             {
51               const char *rhaystack = haystack + 1;
52               const char *rneedle = needle;
53
54               for (;; rhaystack++, rneedle++)
55                 {
56                   if (*rneedle == '\0')
57                     /* Found a match.  */
58                     return (char *) haystack;
59                   if (*rhaystack == '\0')
60                     /* No match.  */
61                     return NULL;
62                   if (TOLOWER ((unsigned char) *rhaystack)
63                       != TOLOWER ((unsigned char) *rneedle))
64                     /* Nothing in this round.  */
65                     break;
66                 }
67             }
68         }
69     }
70   else
71     return (char *) haystack;
72 }