From a17bfec43df0f3d509dba5be74d19c790a7e76e4 Mon Sep 17 00:00:00 2001 From: Juha Niskanen Date: Tue, 10 May 2022 15:02:40 +0300 Subject: [PATCH] libc/string: simplify strrchr Do not call strlen() here. Old implementation iterated over string twice, if searched for position was at the beginning. This commit changes strrchr() to scan string only once, regardless of input. Signed-off-by: Juha Niskanen --- libs/libc/string/lib_strchrnul.c | 2 +- libs/libc/string/lib_strrchr.c | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/libs/libc/string/lib_strchrnul.c b/libs/libc/string/lib_strchrnul.c index ab15fb9600..d338efcc58 100644 --- a/libs/libc/string/lib_strchrnul.c +++ b/libs/libc/string/lib_strchrnul.c @@ -39,7 +39,7 @@ * considered to be part of the string. * * Returned Value: - * Upon completion, strchrnull() returns a pointer to the byte, or a + * Upon completion, strchrnul() returns a pointer to the byte, or a * pointer to null if the byte was not found. * ****************************************************************************/ diff --git a/libs/libc/string/lib_strrchr.c b/libs/libc/string/lib_strrchr.c index 2a04b06c71..6c6b5d961e 100644 --- a/libs/libc/string/lib_strrchr.c +++ b/libs/libc/string/lib_strrchr.c @@ -37,15 +37,16 @@ #undef strrchr /* See mm/README.txt */ FAR char *strrchr(FAR const char *s, int c) { - FAR const char *p = &s[strlen(s)]; + FAR const char *r = NULL; - for (; p >= s; p--) + do { - if (*p == c) + if (*s == c) { - return (FAR char *)p; + r = s; } } + while (*s++ != '\0'); - return NULL; + return (FAR char *)r; }