Re: [PATCH] strchr, strchrnul: implement strchr() as strchrnul()

Richard Earnshaw <[email protected]>
Newsgroups gmane.comp.lib.newlib
Message-ID <[email protected]>

On 05/12/2023 15:52, James wrote:
> Currently, strchrnul() is implemented as strchr() and falls back to a 
> strlen() to find the null-terminator if the character is not 
> found, scanning the string twice. However, strchr() is going to scan the 
> whole string anyway and discard the pointer to the null-terminator if 
> the character is not found, returning NULL.
> 
> Instead, we can just implement strchr() with discarding strchrnul()'s 
> pointer to null-terminator returning NULL and by that avoid calling 
> strlen() in strchrnul() if a character is not found.
> 
> I made a typo in the strchr(), it should be:
>    return s1 && *s1 ? (char *) s1 : NULL;
> which should be:
>    return *s1 ? (char *) s1 : NULL;
> since strchrnul will never return NULL.
> 
> We can avoid the strchrnul() function call in strchr() by implementing 
> it in a separate header like str-two-way.h and including them in both 
> files. The same could be done with the strlen() part in strchr() since 
> the implementations look to be the same.

strchrnul is not standard, it's a GNU extension.  So technically, it 
should be possible to redefine strchrnul to something else and strchr 
should still work as expected.

The other issue is that many ports implement strchr in assembly for 
performance and rely on strchrnul calling that to avoid having too many 
functions implemented in assembly.

So I'm not convinced this is a good idea.

R.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.