This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: [PATCH] Improve memmem.
- From: Paul Eggert <eggert at cs dot ucla dot edu>
- To: OndÅej BÃlka <neleai at seznam dot cz>, libc-alpha at sourceware dot org
- Date: Wed, 13 May 2015 09:31:06 -0700
- Subject: Re: [PATCH] Improve memmem.
- Authentication-results: sourceware.org; auth=none
- References: <20150513000329 dot GA23595 at domone>
OndÅej BÃlka wrote:
+ if (needle_len == 1)
+ return memchr (haystack, needle[0], haystack_end - haystack);
+
+ while ((haystack = memchr (haystack, needle[0], haystack_end - haystack)))
+ {
+ if (haystack[1] == needle[1]
+ && (needle_len == 2 || haystack[2] == needle[2]))
+ {
+ if (needle_len == 2)
+ return haystack;
+
+ if (!memcmp (haystack + 2, needle + 2, needle_len - 2))
+ return haystack;
+ else
+ goto slow_path;
+ }
+ haystack++;
+ }
+
+ return NULL;
+
+ slow_path:;
First, that "haystack[1] == needle[1]" could access past the end of the
haystack. Second, can't this be rewritten to avoid that ugly goto? Something
like the attached, perhaps.
if (needle_len == 1)
return memchr (haystack, needle[0], haystack_end - haystack);
for (; ; haystack++)
{
haystack = memchr (haystack, needle[0],
haystack_end - needle_len + 1 - haystack);
if (!haystack)
return NULL;
if (haystack[1] == needle[1])
{
if (needle_len == 2
|| !memcmp (haystack + 2, needle + 2, needle_len - 2))
return haystack;
break;
}
}