1 #include <memory>
2 #include <stdio.h>
3
4 namespace e
5 {
6 /* XXX: Partially adapted from code which contianed this
7 * copyright:
8 * Byte-wise substring search, using the Two-Way algorithm.
9 * Copyright (C) 2008, 2010 Eric Blake
10 * Permission to use, copy, modify, and distribute this software
11 * is freely granted, provided that this notice is preserved.
12 */
13
14
15
memmem(const void * haystack,size_t haystack_len,const void * needle,size_t needle_len)16 void *memmem(const void *haystack, size_t haystack_len,
17 const void *needle, size_t needle_len)
18 {
19 const char *begin = (const char*)haystack;
20 const char *last_possible = begin + haystack_len - needle_len;
21 const char *tail = (const char*)needle;
22 char point;
23
24 /*
25 * The first occurrence of the empty string is deemed to occur at
26 * the beginning of the string.
27 */
28 if (needle_len == 0)
29 return (void *)begin;
30
31 /*
32 * Sanity check, otherwise the loop might search through the whole
33 * memory.
34 */
35 if (haystack_len < needle_len)
36 return NULL;
37
38 point = *tail++;
39 for (; begin <= last_possible; begin++) {
40 if (*begin == point && !memcmp(begin + 1, tail, needle_len - 1))
41 return (void *)begin;
42 }
43
44 return NULL;
45 }
46 }
47