]> git.ipfire.org Git - thirdparty/bacula.git/commitdiff
Add bstrcasestr() for non GNU platforms
authorEric Bollengier <eric@baculasystems.com>
Wed, 14 Sep 2022 13:36:36 +0000 (15:36 +0200)
committerEric Bollengier <eric@baculasystems.com>
Thu, 14 Sep 2023 11:56:58 +0000 (13:56 +0200)
bacula/src/lib/bsys.c
bacula/src/lib/protos.h

index 2b0a17d69f7f53403e68dbb4474447a1a2724321..c42cb4ee4e10abbdf65e96437051adf8564416e5 100644 (file)
@@ -1879,6 +1879,29 @@ int get_home_directories(const char *grpname, alist *dirs)
    return (dirs->size() > 0) ? 0 : -1;
 }
 
+/* Implementation of strcasestr() for non-gnu platforms */
+char *bstrcasestr(const char *haystack, const char *needle)
+{
+  int needle_len;               /* Length of needle.  */
+  int haystack_len;             /* Known minimum length of haystack.  */
+
+  if (!needle || needle[0] == '\0') {
+     return (char *)haystack;
+  }
+  needle_len = strlen (needle);
+  haystack_len = strlen (haystack);
+
+  const char *p = haystack;
+  while (p && *p && haystack_len >= needle_len) {
+     if (strncasecmp(needle, p, needle_len) == 0) {
+        return (char *)p;
+     }
+     p++;
+     haystack_len--;
+  }
+  return NULL;
+}
+
 #ifdef TEST_PROGRAM
 
 #include "unittests.h"
@@ -2136,6 +2159,17 @@ int main(int argc, char **argv)
       i++;
    }
 
+   // Test bstrcasestr()
+   {
+      const char *p1 = "This is a test";
+      ok(bstrcasestr(p1, "toto") == NULL, "Test with non existing string");
+      ok(bstrcasestr(p1, NULL) == p1, "Test with NULL string");
+      ok(bstrcasestr(p1, "") == p1, "Test with empty string");
+      is(bstrcasestr(p1, "TEST"), "test", "Test with upper string at the end");
+      is(bstrcasestr(p1, "this"), p1, "Test with lower string at the start");
+      ok(bstrcasestr(p1, "xxxxxxxxxxxxxxxxxxxxxxxxx") == NULL, "Test with non existing string");
+      is(bstrcasestr(p1, " iS"), " is a test", "Test with a middle string");
+   }
    return report();
 }
 #endif
index 4348a2facaa23f127f82c9d861e36a25a246da9e..2e5e26ed8ffdcacedfb64a3c598c372721d9fea6 100644 (file)
@@ -74,6 +74,7 @@ const char *get_timezone();
 int get_user_home_directory(const char *user, POOLMEM *&home);
 int get_home_directories(const char *grpname, alist *dirs);
 char *ucfirst(char *dest, const char *src, int len);
+char *bstrcasestr(char *haystack, char *needle);
 typedef enum {
    WAIT_READ  = 1,
    WAIT_WRITE = 2