1 /* Case-insensitive searching in a string.
2 Copyright (C) 2005-2011 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. */
28 #define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch))
30 /* Two-Way algorithm. */
31 #define RETURN_TYPE char *
32 #define AVAILABLE(h, h_l, j, n_l) \
33 (!memchr ((h) + (h_l), '\0', (j) + (n_l) - (h_l)) \
34 && ((h_l) = (j) + (n_l)))
35 #define CANON_ELEMENT(c) TOLOWER (c)
36 #define CMP_FUNC(p1, p2, l) \
37 strncasecmp ((const char *) (p1), (const char *) (p2), l)
38 #include "str-two-way.h"
40 /* Find the first occurrence of NEEDLE in HAYSTACK, using
41 case-insensitive comparison. This function gives unspecified
42 results in multibyte locales. */
44 strcasestr (const char *haystack_start, const char *needle_start)
46 const char *haystack = haystack_start;
47 const char *needle = needle_start;
48 size_t needle_len; /* Length of NEEDLE. */
49 size_t haystack_len; /* Known minimum length of HAYSTACK. */
50 bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
52 /* Determine length of NEEDLE, and in the process, make sure
53 HAYSTACK is at least as long (no point processing all of a long
54 NEEDLE if HAYSTACK is too short). */
55 while (*haystack && *needle)
57 ok &= (TOLOWER ((unsigned char) *haystack)
58 == TOLOWER ((unsigned char) *needle));
65 return (char *) haystack_start;
66 needle_len = needle - needle_start;
67 haystack = haystack_start + 1;
68 haystack_len = needle_len - 1;
70 /* Perform the search. Abstract memory is considered to be an array
71 of 'unsigned char' values, not an array of 'char' values. See
72 ISO C 99 section 6.2.6.1. */
73 if (needle_len < LONG_NEEDLE_THRESHOLD)
74 return two_way_short_needle ((const unsigned char *) haystack,
76 (const unsigned char *) needle_start,
78 return two_way_long_needle ((const unsigned char *) haystack, haystack_len,
79 (const unsigned char *) needle_start,
83 #undef LONG_NEEDLE_THRESHOLD