Skip to content

Commit

Permalink
libc/string: simplify strrchr
Browse files Browse the repository at this point in the history
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 <juha.niskanen@haltian.com>
  • Loading branch information
juniskane committed May 10, 2022
1 parent e2b0d7e commit a3c3cba
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
2 changes: 1 addition & 1 deletion libs/libc/string/lib_strchrnul.c
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
****************************************************************************/
Expand Down
11 changes: 6 additions & 5 deletions libs/libc/string/lib_strrchr.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit a3c3cba

Please sign in to comment.