[systemd-devel] [PATCH 1/2] Optimize startswith() to macro

WANG Chao chaowang at redhat.com
Wed Aug 21 11:15:24 PDT 2013


Take this optimized code from Lennart[1]. Now startswith is a macro using
strncmp and should be fast enough.

[1]: http://lists.freedesktop.org/archives/systemd-devel/2013-July/011860.html
---
 src/shared/macro.h |  5 +++++
 src/shared/util.c  | 17 -----------------
 2 files changed, 5 insertions(+), 17 deletions(-)

diff --git a/src/shared/macro.h b/src/shared/macro.h
index 0d3ff1c..6053a0c 100644
--- a/src/shared/macro.h
+++ b/src/shared/macro.h
@@ -188,6 +188,11 @@ static inline size_t ALIGN_TO(size_t l, size_t ali) {
 
 #define hasprefix(s, prefix) (memcmp(s, prefix, strlen(prefix)) == 0)
 
+#define startswith(s, prefix) ({ \
+        size_t _l = strlen(prefix); \
+        strncmp(s, prefix, _l) == 0 ? s + _l : NULL; \
+})
+
 #define IOVEC_SET_STRING(i, s)                  \
         do {                                    \
                 struct iovec *_i = &(i);        \
diff --git a/src/shared/util.c b/src/shared/util.c
index ca9c2eb..fc89cec 100644
--- a/src/shared/util.c
+++ b/src/shared/util.c
@@ -128,23 +128,6 @@ char* endswith(const char *s, const char *postfix) {
         return (char*) s + sl - pl;
 }
 
-char* startswith(const char *s, const char *prefix) {
-        const char *a, *b;
-
-        assert(s);
-        assert(prefix);
-
-        a = s, b = prefix;
-        for (;;) {
-                if (*b == 0)
-                        return (char*) a;
-                if (*a != *b)
-                        return NULL;
-
-                a++, b++;
-        }
-}
-
 char* startswith_no_case(const char *s, const char *prefix) {
         const char *a, *b;
 
-- 
1.8.3.1



More information about the systemd-devel mailing list