chiark / gitweb /
string-util: add new memory_startswith() helper
authorLennart Poettering <lennart@poettering.net>
Wed, 30 May 2018 11:07:37 +0000 (13:07 +0200)
committerSven Eden <yamakuzure@gmx.net>
Fri, 24 Aug 2018 14:47:08 +0000 (16:47 +0200)
We have code like this at various placer, let's make things shorter and
more readable with a helper for it.

src/basic/string-util.h
src/test/test-string-util.c

index 56a64d7f5a5217f40c2daecc5639995e399154cf..52a1d7f2bee377ae9ff715a4fb3255c8dc412a00 100644 (file)
@@ -217,3 +217,21 @@ static inline size_t strlen_ptr(const char *s) {
 
         return strlen(s);
 }
+
+/* Like startswith(), but operates on arbitrary memory blocks */
+static inline void *memory_startswith(const void *p, size_t sz, const char *token) {
+        size_t n;
+
+        assert(token);
+
+        n = strlen(token);
+        if (sz < n)
+                return NULL;
+
+        assert(p);
+
+        if (memcmp(p, token, n) != 0)
+                return NULL;
+
+        return (uint8_t*) p + n;
+}
index 97f8fde976d4727dd044d2a6c25a3b0acb835744..a7c863c8958f8626c88be92a8b863b423e87c103 100644 (file)
@@ -414,6 +414,18 @@ static void test_strlen_ptr(void) {
         assert_se(strlen_ptr(NULL) == 0);
 }
 
+static void test_memory_startswith(void) {
+        assert_se(streq(memory_startswith("", 0, ""), ""));
+        assert_se(streq(memory_startswith("", 1, ""), ""));
+        assert_se(streq(memory_startswith("x", 2, ""), "x"));
+        assert_se(!memory_startswith("", 1, "x"));
+        assert_se(!memory_startswith("", 1, "xxxxxxxx"));
+        assert_se(streq(memory_startswith("xxx", 4, "x"), "xx"));
+        assert_se(streq(memory_startswith("xxx", 4, "xx"), "x"));
+        assert_se(streq(memory_startswith("xxx", 4, "xxx"), ""));
+        assert_se(!memory_startswith("xxx", 4, "xxxx"));
+}
+
 int main(int argc, char *argv[]) {
         test_string_erase();
 #if 0 /// UNNEEDED by elogind
@@ -449,6 +461,7 @@ int main(int argc, char *argv[]) {
         test_split_pair();
         test_first_word();
         test_strlen_ptr();
+        test_memory_startswith();
 
         return 0;
 }