xref: /freebsd/lib/libc/string/memrchr.c (revision 82e45205c802a06f0663e5f0e4fd2f2f047d2936)
182e45205SXin LI /*	$OpenBSD: memrchr.c,v 1.2 2007/11/27 16:22:12 martynas Exp $	*/
282e45205SXin LI 
382e45205SXin LI /*
482e45205SXin LI  * Copyright (c) 2007 Todd C. Miller <Todd.Miller@courtesan.com>
582e45205SXin LI  *
682e45205SXin LI  * Permission to use, copy, modify, and distribute this software for any
782e45205SXin LI  * purpose with or without fee is hereby granted, provided that the above
882e45205SXin LI  * copyright notice and this permission notice appear in all copies.
982e45205SXin LI  *
1082e45205SXin LI  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
1182e45205SXin LI  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1282e45205SXin LI  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
1382e45205SXin LI  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1482e45205SXin LI  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
1582e45205SXin LI  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1682e45205SXin LI  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1782e45205SXin LI  *
1882e45205SXin LI  * $FreeBSD$
1982e45205SXin LI  */
2082e45205SXin LI 
2182e45205SXin LI #include <string.h>
2282e45205SXin LI 
2382e45205SXin LI /*
2482e45205SXin LI  * Reverse memchr()
2582e45205SXin LI  * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2682e45205SXin LI  */
2782e45205SXin LI void *
2882e45205SXin LI memrchr(const void *s, int c, size_t n)
2982e45205SXin LI {
3082e45205SXin LI 	const unsigned char *cp;
3182e45205SXin LI 
3282e45205SXin LI 	if (n != 0) {
3382e45205SXin LI 		cp = (unsigned char *)s + n;
3482e45205SXin LI 		do {
3582e45205SXin LI 			if (*(--cp) == (unsigned char)c)
3682e45205SXin LI 				return((void *)cp);
3782e45205SXin LI 		} while (--n != 0);
3882e45205SXin LI 	}
3982e45205SXin LI 	return(NULL);
4082e45205SXin LI }
41