From 9b8ff18319965c7e599a70c2a1fab65823b53536 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Wed, 30 May 2018 13:07:37 +0200 Subject: [PATCH] string-util: add new memory_startswith() helper 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 | 18 ++++++++++++++++++ src/test/test-string-util.c | 13 +++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/basic/string-util.h b/src/basic/string-util.h index 5a10eeabfe9..aa007242663 100644 --- a/src/basic/string-util.h +++ b/src/basic/string-util.h @@ -209,3 +209,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; +} diff --git a/src/test/test-string-util.c b/src/test/test-string-util.c index 965e2c5028e..eac12ac7afd 100644 --- a/src/test/test-string-util.c +++ b/src/test/test-string-util.c @@ -406,6 +406,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(); test_ascii_strcasecmp_n(); @@ -433,6 +445,7 @@ int main(int argc, char *argv[]) { test_split_pair(); test_first_word(); test_strlen_ptr(); + test_memory_startswith(); return 0; } -- 2.47.3