aboutsummaryrefslogblamecommitdiffstats
path: root/memmem.c
blob: 5affa16a04f8bebfb034f3e78e0fdf80d03d023d (plain) (tree)
1
2
3

                                                         
            




















                                                                              

 

                 


























                                                                         
/* See LICENSE file for copyright and license details. */
#include "libsimple.h"
#ifndef TEST


void *
libsimple_memmem(const void *hay_, size_t hayn, const void *sub_, size_t subn)
{
	char *hay = (void *)hay_, *end;
	const char *sub = sub_;

	if (!subn)
		return hay;
	if (hayn < subn)
		return NULL;
	if (subn == 1)
		return memchr(hay, *sub, hayn);

	for (end = &hay[hayn - subn + 1]; hay != end; hay++)
		if (*hay == *sub && !memcmp(hay, sub, subn))
			return hay;

	return NULL;
}


#else
#include "test.h"

int
main(void)
{
	assert(!strcmp(libsimple_memmem("test", 4, "test", 4), "test"));
	assert(!strcmp(libsimple_memmem("", 0, "", 0), ""));
	assert(!strcmp(libsimple_memmem("test", 4, "", 0), "test"));
	assert(!libsimple_memmem("", 0, "test", 4));
	assert(!libsimple_memmem("t", 1, "test", 4));
	assert(!strcmp(libsimple_memmem("test", 4, "t", 1), "test"));
	assert(!strcmp(libsimple_memmem("test", 4, "e", 1), "est"));
	assert(!strcmp(libsimple_memmem("test", 4, "s", 1), "st"));
	assert(!libsimple_memmem("test", 4, "x", 1));
	assert(!strcmp(libsimple_memmem("test", 4, "te", 2), "test"));
	assert(!strcmp(libsimple_memmem("test", 4, "es", 2), "est"));
	assert(!strcmp(libsimple_memmem("test", 4, "st", 2), "st"));
	assert(!strcmp(libsimple_memmem("test", 5, "t", 2), "t"));
	assert(!libsimple_memmem("test", 4, "xx", 2));
	assert(!strcmp(libsimple_memmem("abc", 3, "c", 1), "c"));
	assert(!strcmp(libsimple_memmem("abc", 3, "bc", 2), "bc"));
	assert(!strcmp(libsimple_memmem("abc", 3, "abc", 3), "abc"));
	assert(!libsimple_memmem("abc", 3, "abc", 4));
	assert(!strcmp(libsimple_memmem("abcabc", 6, "bc", 2), "bcabc"));
	return 0;
}

#endif