1 /* Copyright (C) 1991-1994, 1996-1998, 2000, 2004, 2007-2012 Free Software 2 Foundation, Inc. 3 This file is part of the GNU C Library. 4 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, or (at your option) 8 any later version. 9 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. 14 15 You should have received a copy of the GNU General Public License along 16 with this program; if not, see <http://www.gnu.org/licenses/>. */ 17 18 /* This particular implementation was written by Eric Blake, 2008. */ 19 20 #ifndef _LIBC 21 # include <config.h> 22 #endif 23 24 /* Specification of memmem. */ 25 #include <string.h> 26 27 #ifndef _LIBC 28 # define __builtin_expect(expr, val) (expr) 29 #endif 30 31 #define RETURN_TYPE void * 32 #define AVAILABLE(h, h_l, j, n_l) ((j) <= (h_l) - (n_l)) 33 #include "str-two-way.h" 34 35 /* Return the first occurrence of NEEDLE in HAYSTACK. Return HAYSTACK 36 if NEEDLE_LEN is 0, otherwise NULL if NEEDLE is not found in 37 HAYSTACK. */ 38 void * 39 memmem (const void *haystack_start, size_t haystack_len, 40 const void *needle_start, size_t needle_len) 41 { 42 /* Abstract memory is considered to be an array of 'unsigned char' values, 43 not an array of 'char' values. See ISO C 99 section 6.2.6.1. */ 44 const unsigned char *haystack = (const unsigned char *) haystack_start; 45 const unsigned char *needle = (const unsigned char *) needle_start; 46 47 if (needle_len == 0) 48 /* The first occurrence of the empty string is deemed to occur at 49 the beginning of the string. */ 50 return (void *) haystack; 51 52 /* Sanity check, otherwise the loop might search through the whole 53 memory. */ 54 if (__builtin_expect (haystack_len < needle_len, 0)) 55 return NULL; 56 57 /* Use optimizations in memchr when possible, to reduce the search 58 size of haystack using a linear algorithm with a smaller 59 coefficient. However, avoid memchr for long needles, since we 60 can often achieve sublinear performance. */ 61 if (needle_len < LONG_NEEDLE_THRESHOLD) 62 { 63 haystack = memchr (haystack, *needle, haystack_len); 64 if (!haystack || __builtin_expect (needle_len == 1, 0)) 65 return (void *) haystack; 66 haystack_len -= haystack - (const unsigned char *) haystack_start; 67 if (haystack_len < needle_len) 68 return NULL; 69 return two_way_short_needle (haystack, haystack_len, needle, needle_len); 70 } 71 else 72 return two_way_long_needle (haystack, haystack_len, needle, needle_len); 73 } 74 75 #undef LONG_NEEDLE_THRESHOLD 76