aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorVladimir Gavrilov <105977161+0xA50C1A1@users.noreply.github.com>2024-05-10 23:43:59 +0300
committerGitHub <noreply@github.com>2024-05-10 22:43:59 +0200
commita813121e0a7021cdbfd64630960b330a23b1a4d2 (patch)
tree7021b987d621b6940ebccc6738967654c399d477 /src
parent4b4b358562a80b546d10f779dba8c56c5d0c6502 (diff)
`ndpi_strnstr()` optimization (#2433)
Diffstat (limited to 'src')
-rw-r--r--src/lib/ndpi_main.c47
1 files changed, 32 insertions, 15 deletions
diff --git a/src/lib/ndpi_main.c b/src/lib/ndpi_main.c
index ada8129b2..2752aa55f 100644
--- a/src/lib/ndpi_main.c
+++ b/src/lib/ndpi_main.c
@@ -9676,25 +9676,42 @@ void ndpi_dump_risks_score(FILE *risk_out) {
* 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) {
+ return NULL;
+ }
+
+ char c = *find;
+
+ if (c == '\0') {
+ return (char *)s;
+ }
+
+ if (*(find + 1) == '\0') {
+ return (char *)memchr(s, c, slen);
+ }
+
+ size_t find_len = strnlen(find, slen);
- if((c = *find++) != '\0') {
- len = strnlen(find, slen);
- do {
- char sc;
+ if (find_len > slen) {
+ return NULL;
+ }
+
+ const char *end = s + slen - find_len;
+
+ while (s <= end) {
+ if (memcmp(s, find, find_len) == 0) {
+ return (char *)s;
+ }
- do {
- if(slen-- < 1 || (sc = *s++) == '\0')
- return(NULL);
- } while(sc != c);
- if(len > slen)
- return(NULL);
- } while(strncmp(s, find, len) != 0);
- s--;
+ size_t remaining_length = end - s;
+ s = (char *)memchr(s + 1, c, remaining_length);
+
+ if (s == NULL || s > end) {
+ return NULL;
+ }
}
- return((char *) s);
+ return NULL;
}
/* ****************************************************** */