This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [PATCH] Improve memmem.


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;
	}
    }

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]