[PATCH] add memrchr(3)

Gregory Pietsch gpietsch@comcast.net
Thu May 10 07:25:00 GMT 2012


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
>



More information about the Newlib mailing list