-
Notifications
You must be signed in to change notification settings - Fork 0
/
memmem.c
35 lines (24 loc) · 1020 Bytes
/
memmem.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include "config.h"
/* We only need this memmem() function if it doesn't exist in the C
library. It exists in GNU libc and on MacOS, but apparently not on
Windows. */
#ifndef HAVE_MEMMEM
#include <string.h> /* We use memcmp() */
#include <assert.h>
#include "export.h"
/* memmem -- locate a byte substring in a byte string */
EXPORT void *memmem(const void *haystack, size_t haystacklen,
const void *needle, size_t needlelen)
{
/* If haystack is NULL, haystacklen must be 0. Ditto for needle. */
assert(needlelen == 0 || needle != NULL);
assert(haystacklen == 0 || haystack != NULL);
/* Per the manual page on MacOS, return NULL if needlelen == 0. */
if (needlelen == 0) return NULL;
/* Iterate over the haystack to find the first match for needle. */
for (; haystacklen >= needlelen; haystacklen--, haystack++)
if (memcmp(haystack, needle, needlelen) == 0) return haystack;
/* The haystack is now too short to contain the needle. */
return NULL;
}
#endif /* HAVE_MEMMEM */