1/* Case-insensitive searching in a string. 2 Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, 3 Inc. 4 Written by Bruno Haible <bruno@clisp.org>, 2005. 5 6 This program is free software; you can redistribute it and/or modify 7 it under the terms of the GNU General Public License as published by 8 the Free Software Foundation; either version 3, or (at your option) 9 any later version. 10 11 This program is distributed in the hope that it will be useful, 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU General Public License for more details. 15 16 You should have received a copy of the GNU General Public License 17 along with this program; if not, write to the Free Software Foundation, 18 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ 19 20#include <config.h> 21 22/* Specification. */ 23#include <string.h> 24 25#include <ctype.h> 26#include <stdbool.h> 27#include <strings.h> 28 29#define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch)) 30 31/* Two-Way algorithm. */ 32#define RETURN_TYPE char * 33#define AVAILABLE(h, h_l, j, n_l) \ 34 (!memchr ((h) + (h_l), '\0', (j) + (n_l) - (h_l)) \ 35 && ((h_l) = (j) + (n_l))) 36#define CANON_ELEMENT(c) TOLOWER (c) 37#define CMP_FUNC(p1, p2, l) \ 38 strncasecmp ((const char *) (p1), (const char *) (p2), l) 39#include "str-two-way.h" 40 41/* Find the first occurrence of NEEDLE in HAYSTACK, using 42 case-insensitive comparison. This function gives unspecified 43 results in multibyte locales. */ 44char * 45strcasestr (const char *haystack_start, const char *needle_start) 46{ 47 const char *haystack = haystack_start; 48 const char *needle = needle_start; 49 size_t needle_len; /* Length of NEEDLE. */ 50 size_t haystack_len; /* Known minimum length of HAYSTACK. */ 51 bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */ 52 53 /* Determine length of NEEDLE, and in the process, make sure 54 HAYSTACK is at least as long (no point processing all of a long 55 NEEDLE if HAYSTACK is too short). */ 56 while (*haystack && *needle) 57 { 58 ok &= (TOLOWER ((unsigned char) *haystack) 59 == TOLOWER ((unsigned char) *needle)); 60 haystack++; 61 needle++; 62 } 63 if (*needle) 64 return NULL; 65 if (ok) 66 return (char *) haystack_start; 67 needle_len = needle - needle_start; 68 haystack = haystack_start + 1; 69 haystack_len = needle_len - 1; 70 71 /* Perform the search. Abstract memory is considered to be an array 72 of 'unsigned char' values, not an array of 'char' values. See 73 ISO C 99 section 6.2.6.1. */ 74 if (needle_len < LONG_NEEDLE_THRESHOLD) 75 return two_way_short_needle ((const unsigned char *) haystack, 76 haystack_len, 77 (const unsigned char *) needle_start, 78 needle_len); 79 return two_way_long_needle ((const unsigned char *) haystack, haystack_len, 80 (const unsigned char *) needle_start, 81 needle_len); 82} 83 84#undef LONG_NEEDLE_THRESHOLD 85