Skip to content

Commit 8daf318

Browse files
committed
Add rt_strnstr function and its configuration options to support finding substrings within a specified maximum length
1 parent 88a4474 commit 8daf318

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

include/klibc/kstring.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ rt_int32_t rt_memcmp(const void *cs, const void *ct, rt_size_t count);
2525
char *rt_strdup(const char *s);
2626
rt_size_t rt_strnlen(const char *s, rt_ubase_t maxlen);
2727
char *rt_strstr(const char *str1, const char *str2);
28+
char *rt_strnstr(const char *s1, const char *s2, rt_size_t maxlen);
2829
rt_int32_t rt_strcasecmp(const char *a, const char *b);
2930
char *rt_strcpy(char *dst, const char *src);
3031
char *rt_strncpy(char *dest, const char *src, rt_size_t n);

src/klibc/Kconfig

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,12 @@ menu "klibc options"
178178
endif
179179
endmenu # rt_strstr options
180180

181+
menu "rt_strnstr options"
182+
config RT_KLIBC_USING_USER_STRNSTR
183+
bool "Enable rt_strnstr to use user-defined version"
184+
default n
185+
endmenu # rt_strnstr options
186+
181187
menu "rt_strcasecmp options"
182188
config RT_KLIBC_USING_USER_STRCASECMP
183189
bool "Enable rt_strcasecmp to use user-defined version"

src/klibc/kstring.c

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,62 @@ char *rt_strstr(const char *s1, const char *s2)
313313
#endif /* RT_KLIBC_USING_USER_STRSTR */
314314
RTM_EXPORT(rt_strstr);
315315

316+
/**
317+
* @brief This function will return the first occurrence of a string, without the
318+
* terminator '\0'.
319+
*
320+
* @param s1 is the source string.
321+
*
322+
* @param s2 is the find string.
323+
*
324+
* @param maxlen is the max size.
325+
*
326+
* @return The first occurrence of a s2 in s1, or RT_NULL if no found.
327+
*/
328+
#ifndef RT_KLIBC_USING_USER_STRNSTR
329+
char *rt_strnstr(const char *s1, const char *s2, rt_size_t maxlen)
330+
{
331+
rt_size_t l1 = 0, l2 = 0;
332+
int max_pos = 0;
333+
334+
l2 = rt_strlen(s2);
335+
if (!l2)
336+
{
337+
return (char *)s1;
338+
}
339+
340+
l1 = rt_strlen(s1);
341+
if (!l1)
342+
{
343+
return RT_NULL;
344+
}
345+
346+
max_pos = maxlen < l1 ? maxlen : l1;
347+
if (max_pos < l2)
348+
{
349+
return RT_NULL;
350+
}
351+
352+
max_pos = max_pos - l2;
353+
while (max_pos >= 0)
354+
{
355+
if (*s1 == *s2)
356+
{
357+
if (!rt_strncmp(s1, s2, l2))
358+
{
359+
return (char *)s1;
360+
}
361+
}
362+
363+
s1++;
364+
max_pos--;
365+
}
366+
367+
return RT_NULL;
368+
}
369+
#endif /* RT_KLIBC_USING_USER_STRNSTR */
370+
RTM_EXPORT(rt_strnstr);
371+
316372
/**
317373
* @brief This function will compare two strings while ignoring differences in case
318374
*

0 commit comments

Comments
 (0)