Replace ndpi_strnstr() implementation with an optimal one (#2447)

This commit is contained in:
Vladimir Gavrilov
2024-05-22 12:47:27 +02:00
committed by GitHub
parent 5a25f89ab3
commit 15643547fe
3 changed files with 115 additions and 65 deletions
+8 -8
View File
@@ -115,17 +115,17 @@ extern "C" {
u_int32_t ndpi_get_tot_allocated_memory(void);
/**
* Search the first occurrence of substring -find- in -s-
* The search is limited to the first -slen- characters of the string
* Finds the first occurrence of the substring 'needle' in the string 'haystack'.
*
* @par s = string to parse
* @par find = string to match with -s-
* @par slen = max length to match between -s- and -find-
* @return a pointer to the beginning of the located substring;
* NULL if the substring is not found
* This function is similar to the standard `strstr()` function, but it has an additional parameter `len` that
* specifies the maximum length of the search.
*
* @param haystack The string to search in.
* @param needle The substring to search for.
* @param len The maximum length of the search.
* @return Pointer to the first occurrence of 'needle' in 'haystack', or NULL if no match is found.
*/
char* ndpi_strnstr(const char *s, const char *find, size_t slen);
char *ndpi_strnstr(const char *haystack, const char *needle, size_t len);
/**
* Same as ndpi_strnstr but case insensitive
+44 -24
View File
@@ -9610,32 +9610,52 @@ void ndpi_dump_risks_score(FILE *risk_out) {
/* ****************************************************** */
/*
* Find the first occurrence of find in s, where the search is limited to the
* first slen characters of s.
*/
char *ndpi_strnstr(const char *s, const char *find, size_t slen) {
char c;
size_t len;
if(s == NULL || find == NULL || slen == 0)
char *ndpi_strnstr(const char *haystack, const char *needle, size_t len)
{
if (!haystack || !needle || len == 0)
{
return NULL;
if((c = *find++) != '\0') {
len = strnlen(find, slen);
do {
char sc;
do {
if(slen-- < 1 || (sc = *s++) == '\0')
return(NULL);
} while(sc != c);
if(len > slen)
return(NULL);
} while(strncmp(s, find, len) != 0);
s--;
}
return((char *) s);
size_t needle_len = strlen(needle);
size_t hs_real_len = strnlen(haystack, len);
if (needle_len == 0)
{
return (char *)haystack;
}
if (needle_len > hs_real_len)
{
return NULL;
}
if (needle_len == 1)
{
return (char *)memchr(haystack, *needle, hs_real_len);
}
const char *current = haystack;
const char *haystack_end = haystack + hs_real_len;
while (current <= haystack_end - needle_len)
{
current = (const char *)memchr(current, *needle, haystack_end - current);
if (!current)
{
return NULL;
}
if ((current + needle_len <= haystack_end) && memcmp(current, needle, needle_len) == 0)
{
return (char *)current;
}
current++;
}
return NULL;
}
/* ****************************************************** */