execute, spawn-pipe: Make multithread-safe on native Windows.
[gnulib.git] / lib / c-strcasestr.c
blobb55b31f5a0d50a5e1ccb697b89d9f9983bbadbb3
1 /* c-strcasestr.c -- case insensitive substring search in C locale
2 Copyright (C) 2005-2020 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 3 of the License, or
8 (at your option) any later version.
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, see <https://www.gnu.org/licenses/>. */
18 #include <config.h>
20 /* Specification. */
21 #include "c-strcasestr.h"
23 #include <stdbool.h>
24 #include <string.h>
26 #include "c-ctype.h"
27 #include "c-strcase.h"
29 /* Two-Way algorithm. */
30 #define RETURN_TYPE char *
31 #define AVAILABLE(h, h_l, j, n_l) \
32 (!memchr ((h) + (h_l), '\0', (j) + (n_l) - (h_l)) \
33 && ((h_l) = (j) + (n_l)))
34 #define CANON_ELEMENT c_tolower
35 #define CMP_FUNC(p1, p2, l) \
36 c_strncasecmp ((const char *) (p1), (const char *) (p2), l)
37 #include "str-two-way.h"
39 /* Find the first occurrence of NEEDLE in HAYSTACK, using case-insensitive
40 comparison from the C locale, regardless of the current locale. */
41 char *
42 c_strcasestr (const char *haystack_start, const char *needle_start)
44 const char *haystack = haystack_start;
45 const char *needle = needle_start;
46 size_t needle_len; /* Length of NEEDLE. */
47 size_t haystack_len; /* Known minimum length of HAYSTACK. */
48 bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
50 /* Determine length of NEEDLE, and in the process, make sure
51 HAYSTACK is at least as long (no point processing all of a long
52 NEEDLE if HAYSTACK is too short). */
53 while (*haystack && *needle)
54 ok &= (c_tolower ((unsigned char) *haystack++)
55 == c_tolower ((unsigned char) *needle++));
56 if (*needle)
57 return NULL;
58 if (ok)
59 return (char *) haystack_start;
60 needle_len = needle - needle_start;
61 haystack = haystack_start + 1;
62 haystack_len = needle_len - 1;
64 /* Perform the search. Abstract memory is considered to be an array
65 of 'unsigned char' values, not an array of 'char' values. See
66 ISO C 99 section 6.2.6.1. */
67 if (needle_len < LONG_NEEDLE_THRESHOLD)
68 return two_way_short_needle ((const unsigned char *) haystack,
69 haystack_len,
70 (const unsigned char *) needle_start,
71 needle_len);
72 return two_way_long_needle ((const unsigned char *) haystack, haystack_len,
73 (const unsigned char *) needle_start,
74 needle_len);
77 #undef LONG_NEEDLE_THRESHOLD