xref: /netbsd-src/external/gpl3/gcc.old/dist/libiberty/memmem.c (revision b7b7574d3bf8eeb51a1fa3977b59142ec6434a55)
1 /* Copyright (C) 1991,92,93,94,96,97,98,2000,2004,2007 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License along
15    with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17 
18 /*
19 
20 @deftypefn Supplemental void* memmem (const void *@var{haystack}, size_t @var{haystack_len} const void *@var{needle}, size_t @var{needle_len})
21 
22 Returns a pointer to the first occurrence of @var{needle} (length
23 @var{needle_len}) in @var{haystack} (length @var{haystack_len}).
24 Returns @code{NULL} if not found.
25 
26 @end deftypefn
27 
28 */
29 
30 #ifndef _LIBC
31 # include <config.h>
32 #endif
33 
34 #include <stddef.h>
35 #include <string.h>
36 
37 #ifndef _LIBC
38 # define __builtin_expect(expr, val)   (expr)
39 #endif
40 
41 #undef memmem
42 
43 /* Return the first occurrence of NEEDLE in HAYSTACK.  */
44 void *
45 memmem (const void *haystack, size_t haystack_len, const void *needle,
46 	size_t needle_len)
47 {
48   const char *begin;
49   const char *const last_possible
50     = (const char *) haystack + haystack_len - needle_len;
51 
52   if (needle_len == 0)
53     /* The first occurrence of the empty string is deemed to occur at
54        the beginning of the string.  */
55     return (void *) haystack;
56 
57   /* Sanity check, otherwise the loop might search through the whole
58      memory.  */
59   if (__builtin_expect (haystack_len < needle_len, 0))
60     return NULL;
61 
62   for (begin = (const char *) haystack; begin <= last_possible; ++begin)
63     if (begin[0] == ((const char *) needle)[0] &&
64 	!memcmp ((const void *) &begin[1],
65 		 (const void *) ((const char *) needle + 1),
66 		 needle_len - 1))
67       return (void *) begin;
68 
69   return NULL;
70 }
71