swh:1:snp:47f1e8bb459169b0feb652a9c3d9cbabd8526d4a
Raw File
Tip revision: eea591373e139fc8aab89a78ccb0b1512a2bf0de authored by Junio C Hamano on 09 May 2014, 17:59:07 UTC
Git 1.9.3
Tip revision: eea5913
memmem.c
#include "../git-compat-util.h"

void *gitmemmem(const void *haystack, size_t haystack_len,
                const void *needle, size_t needle_len)
{
	const char *begin = haystack;
	const char *last_possible = begin + haystack_len - needle_len;
	const char *tail = needle;
	char point;

	/*
	 * The first occurrence of the empty string is deemed to occur at
	 * the beginning of the string.
	 */
	if (needle_len == 0)
		return (void *)begin;

	/*
	 * Sanity check, otherwise the loop might search through the whole
	 * memory.
	 */
	if (haystack_len < needle_len)
		return NULL;

	point = *tail++;
	for (; begin <= last_possible; begin++) {
		if (*begin == point && !memcmp(begin + 1, tail, needle_len - 1))
			return (void *)begin;
	}

	return NULL;
}
back to top