From ebff1072681c5ed09bb70d9c4f617476822db757 Mon Sep 17 00:00:00 2001 From: Ambroise Vincent Date: Wed, 19 Jun 2019 17:14:09 +0100 Subject: [PATCH] libc: add memrchr This function scans a string backwards from the end for the first instance of a character. Change-Id: I46b21573ed25a0ff222eac340e1e1fb93b040763 Signed-off-by: Ambroise Vincent --- include/lib/libc/string.h | 3 ++- lib/libc/libc.mk | 1 + lib/libc/memrchr.c | 24 ++++++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 lib/libc/memrchr.c diff --git a/include/lib/libc/string.h b/include/lib/libc/string.h index ee6eeacef..de20f6189 100644 --- a/include/lib/libc/string.h +++ b/include/lib/libc/string.h @@ -4,7 +4,7 @@ * SPDX-License-Identifier: BSD-3-Clause */ /* - * Portions copyright (c) 2018, ARM Limited and Contributors. + * Portions copyright (c) 2018-2019, ARM Limited and Contributors. * All rights reserved. */ @@ -23,6 +23,7 @@ int memcmp(const void *s1, const void *s2, size_t len); int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); void *memchr(const void *src, int c, size_t len); +void *memrchr(const void *src, int c, size_t len); char *strchr(const char *s, int c); void *memset(void *dst, int val, size_t count); size_t strlen(const char *s); diff --git a/lib/libc/libc.mk b/lib/libc/libc.mk index e1b5560f8..93d30d035 100644 --- a/lib/libc/libc.mk +++ b/lib/libc/libc.mk @@ -12,6 +12,7 @@ LIBC_SRCS := $(addprefix lib/libc/, \ memcmp.c \ memcpy.c \ memmove.c \ + memrchr.c \ memset.c \ printf.c \ putchar.c \ diff --git a/lib/libc/memrchr.c b/lib/libc/memrchr.c new file mode 100644 index 000000000..01caef3ae --- /dev/null +++ b/lib/libc/memrchr.c @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2019, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +#undef memrchr + +void *memrchr(const void *src, int c, size_t len) +{ + const unsigned char *s = src + (len - 1); + + while (len--) { + if (*s == (unsigned char)c) { + return (void*) s; + } + + s--; + } + + return NULL; +}