Add memmem() implementation (#2378)

* Add memmem() implementation

* Fix build

* Add fix to avoid too many memcmp calls
This commit is contained in:
Vladimir Gavrilov
2024-04-10 15:39:08 +02:00
committed by GitHub
parent 1d0be6c4f4
commit 142c8f5afb
2 changed files with 41 additions and 0 deletions
+13
View File
@@ -2219,6 +2219,19 @@ extern "C" {
const char *ndpi_lru_cache_idx_to_name(lru_cache_type idx);
/**
* Searches for a subsequence ('needle') within a block of memory ('haystack').
*
* @par haystack = pointer to the block of memory where the search is performed
* @par haystack_len = length of the haystack block of memory
* @par needle = pointer to the memory block representing the needle to search for
* @par needle_len = length of the needle memory block
*
* @return Pointer to the beginning of the needle within the haystack if found;
* otherwise, NULL.
*/
void* ndpi_memmem(const void* haystack, size_t haystack_len, const void* needle,
size_t needle_len);
#ifdef __cplusplus
}
+28
View File
@@ -11447,3 +11447,31 @@ char *ndpi_dump_config(struct ndpi_detection_module_struct *ndpi_str,
}
return NULL;
}
void* ndpi_memmem(const void* haystack, size_t haystack_len, const void* needle, size_t needle_len)
{
if (!haystack || !needle) {
return NULL;
}
if (needle_len > haystack_len) {
return NULL;
}
if ((size_t)(const u_int8_t*)haystack+haystack_len < haystack_len) {
return NULL;
}
if (needle_len == 1) {
return memchr(haystack, *(int*)needle, haystack_len);
}
const u_int8_t* h = NULL;
const u_int8_t* n = (const u_int8_t*)needle;
for (h = haystack; h <= (const u_int8_t*)haystack+haystack_len-needle_len; ++h) {
if (*h == n[0] && !memcmp(h, needle, needle_len))
return (void*)h;
}
return NULL;
}