Sync with glibc.
[gnulib.git] / lib / memmem.c
1 /* Copyright (C) 1991,92,93,94,96,97,98,2000,2004 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 #include <stddef.h>
19 #include <string.h>
20
21 #ifndef _LIBC
22 # define __builtin_expect(expr, val)   (expr)
23 #endif
24
25 #undef memmem
26
27 /* Return the first occurrence of NEEDLE in HAYSTACK.  */
28 void *
29 memmem (haystack, haystack_len, needle, needle_len)
30      const void *haystack;
31      size_t haystack_len;
32      const void *needle;
33      size_t needle_len;
34 {
35   const char *begin;
36   const char *const last_possible
37     = (const char *) haystack + haystack_len - needle_len;
38
39   if (needle_len == 0)
40     /* The first occurrence of the empty string is deemed to occur at
41        the beginning of the string.  */
42     return (void *) haystack;
43
44   /* Sanity check, otherwise the loop might search through the whole
45      memory.  */
46   if (__builtin_expect (haystack_len < needle_len, 0))
47     return NULL;
48
49   for (begin = (const char *) haystack; begin <= last_possible; ++begin)
50     if (begin[0] == ((const char *) needle)[0] &&
51         !memcmp ((const void *) &begin[1],
52                  (const void *) ((const char *) needle + 1),
53                  needle_len - 1))
54       return (void *) begin;
55
56   return NULL;
57 }