intrinsic.texi: Explicitly state that ETIME and DTIME take REAL(4) arguments.
[official-gcc.git] / libiberty / memmem.c
blob5d755992b76ec5f3a5d3087845ec722ea2e65a08
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.
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.
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.
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. */
20 @deftypefn Supplemental void* memmem (const void *@var{haystack}, size_t @var{haystack_len} const void *@var{needle}, size_t @var{needle_len})
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.
26 @end deftypefn
30 #ifndef _LIBC
31 # include <config.h>
32 #endif
34 #include <stddef.h>
35 #include <string.h>
37 #ifndef _LIBC
38 # define __builtin_expect(expr, val) (expr)
39 #endif
41 #undef memmem
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)
48 const char *begin;
49 const char *const last_possible
50 = (const char *) haystack + haystack_len - needle_len;
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;
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;
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;
69 return NULL;