blob: 56bcb4277f47c295993c853a84edfe45e6aa3911 [file] [log] [blame]
René Scharfeb21b9f12007-09-07 00:32:54 +02001#include "../git-compat-util.h"
2
3void *gitmemmem(const void *haystack, size_t haystack_len,
4 const void *needle, size_t needle_len)
5{
6 const char *begin = haystack;
7 const char *last_possible = begin + haystack_len - needle_len;
René Scharfe56384e62009-03-03 00:19:30 +01008 const char *tail = needle;
9 char point;
René Scharfeb21b9f12007-09-07 00:32:54 +020010
11 /*
12 * The first occurrence of the empty string is deemed to occur at
13 * the beginning of the string.
14 */
15 if (needle_len == 0)
16 return (void *)begin;
17
18 /*
19 * Sanity check, otherwise the loop might search through the whole
20 * memory.
21 */
22 if (haystack_len < needle_len)
23 return NULL;
24
René Scharfe56384e62009-03-03 00:19:30 +010025 point = *tail++;
René Scharfeb21b9f12007-09-07 00:32:54 +020026 for (; begin <= last_possible; begin++) {
René Scharfe56384e62009-03-03 00:19:30 +010027 if (*begin == point && !memcmp(begin + 1, tail, needle_len - 1))
René Scharfeb21b9f12007-09-07 00:32:54 +020028 return (void *)begin;
29 }
30
31 return NULL;
32}