This is the mail archive of the
newlib@sourceware.org
mailing list for the newlib project.
Re: [PATCH] add memrchr(3)
- From: Gregory Pietsch <gpietsch at comcast dot net>
- To: "Yaakov (Cygwin/X)" <yselkowitz at users dot sourceforge dot net>
- Cc: newlib at sourceware dot org
- Date: Wed, 09 May 2012 14:42:37 -0400
- Subject: Re: [PATCH] add memrchr(3)
- References: <1336550823.8880.2.camel@YAAKOV04>
I have been thinking of how many crazy ways there are to implement
memrchr as a result of this discussion.
First, the usual way:
#include<string.h>
/* memrchr */
void *(memrchr)(const void *s, int c, size_t n)
{
const unsigned char *src= s;
unsigned char uc= c;
src += n - 1;
while (src >= (const unsigned char *) s) {
if (*src== uc)
return (void *) src;
--src;
}
return NULL;
}
I was also thinking recursion. Maybe that would be faster:
#include<string.h>
/* memrchr */
void *(memrchr)(const void *s, int c, size_t n)
{
const unsigned char *src= s;
unsigned char uc= c;
return n ? (src[n - 1] == uc ? (void *) (src + n - 1)
: memrchr (s, c, n - 1)) : 0;
}
What does everyone think?
Gregory
On 5/9/2012 4:07 AM, Yaakov (Cygwin/X) wrote:
This patch adds memrchr(3), a GNU extension also found in the BSDs:
http://man7.org/linux/man-pages/man3/memrchr.3.html
This patch is based on strrchr's usage of strchr.
Patch and new file attached.
Yaakov
Cygwin/X