1 /* Copyright (C) 1991-1994, 1996-1998, 2000, 2004, 2007-2024 Free Software
3 This file is part of the GNU C Library.
5 This file is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as
7 published by the Free Software Foundation; either version 2.1 of the
8 License, or (at your option) any later version.
10 This file 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 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* This particular implementation was written by Eric Blake, 2008. */
24 /* Specification of strstr. */
27 #define RETURN_TYPE char *
28 #define AVAILABLE(h, h_l, j, n_l) \
29 (!memchr ((h) + (h_l), '\0', (j) + (n_l) - (h_l)) \
30 && ((h_l) = (j) + (n_l)))
31 #include "str-two-way.h"
33 /* Return the first occurrence of NEEDLE in HAYSTACK. Return HAYSTACK
34 if NEEDLE is empty, otherwise NULL if NEEDLE is not found in
37 strstr (const char *haystack_start
, const char *needle_start
)
39 const char *haystack
= haystack_start
;
40 const char *needle
= needle_start
;
41 size_t needle_len
; /* Length of NEEDLE. */
42 size_t haystack_len
; /* Known minimum length of HAYSTACK. */
43 bool ok
= true; /* True if NEEDLE is prefix of HAYSTACK. */
45 /* Determine length of NEEDLE, and in the process, make sure
46 HAYSTACK is at least as long (no point processing all of a long
47 NEEDLE if HAYSTACK is too short). */
48 while (*haystack
&& *needle
)
49 ok
&= *haystack
++ == *needle
++;
53 return (char *) haystack_start
;
55 /* Reduce the size of haystack using strchr, since it has a smaller
56 linear coefficient than the Two-Way algorithm. */
57 needle_len
= needle
- needle_start
;
58 haystack
= strchr (haystack_start
+ 1, *needle_start
);
59 if (!haystack
|| __builtin_expect (needle_len
== 1, 0))
60 return (char *) haystack
;
62 haystack_len
= (haystack
> haystack_start
+ needle_len
? 1
63 : needle_len
+ haystack_start
- haystack
);
65 /* Perform the search. Abstract memory is considered to be an array
66 of 'unsigned char' values, not an array of 'char' values. See
67 ISO C 99 section 6.2.6.1. */
68 if (needle_len
< LONG_NEEDLE_THRESHOLD
)
69 return two_way_short_needle ((const unsigned char *) haystack
,
71 (const unsigned char *) needle
, needle_len
);
72 return two_way_long_needle ((const unsigned char *) haystack
, haystack_len
,
73 (const unsigned char *) needle
, needle_len
);
76 #undef LONG_NEEDLE_THRESHOLD