[PATCH 1/3] lib: implement strnstr()
Jerome Forissier
jerome.forissier at linaro.org
Mon Jan 6 11:22:35 CET 2025
On 1/6/25 11:14, Rasmus Villemoes wrote:
> On Mon, Jan 06 2025, Jerome Forissier <jerome.forissier at linaro.org> wrote:
>
>>> + *
>>> + * Return: pointer to the first occurrence or NULL
>>> */
>>> -char * strstr(const char * s1,const char * s2)
>>> +char *strnstr(const char *s1, const char *s2, size_t len)
>>> {
>>> - int l1, l2;
>>> + size_t l1, l2;
>>>
>>> + l1 = strnlen(s1, len);
>>> l2 = strlen(s2);
>>> - if (!l2)
>>> - return (char *) s1;
>>> - l1 = strlen(s1);
>>> - while (l1 >= l2) {
>>> - l1--;
>>> - if (!memcmp(s1,s2,l2))
>>> +
>>> + for (; l1 >= l2; --l1, ++s1) {
>>> + if (!memcmp(s1, s2, l2))
>>> return (char *) s1;
>>> - s1++;
>>> }
>>> +
>>> return NULL;
>>> }
>>> #endif
>>
>> This won't return s1 when s2 == NULL, will it?
>
> Why should it? That's a broken caller. You can't call str* functions
> with NULL pointers. It's ok for s2 to point at an empty string, in which
> case l2 is 0, so the very first memcmp() is guaranteed to succeed and
> yes, this will return s1 in that case.
Sorry I read the strncmp() man page too quickly and mistook empty string
for NULL :-/
>
> As passing "" as s2 is likely quite rare, the current short-circuiting
> of that case is pointless.
Agreed.
>> Why not use a known good implementation such as [1]?
>>
>> [1] https://github.com/freebsd/freebsd-src/blob/main/lib/libc/string/strnstr.c
>
> Licensing?
Isn't BSD compatible with GPL?
> Also, that's quite unreadable, so please don't.
OK.
> Rasmus
--
Jerome
More information about the U-Boot
mailing list