summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLennart Poettering <lennart@poettering.net>2018-03-27 14:56:29 +0200
committerSven Eden <yamakuzure@gmx.net>2018-08-24 16:47:08 +0200
commit961c23bd227db449039af8208733ac5927b8bf0f (patch)
treefb344b42e952b869f10df42f317d6f217998a912
parentabde16c130f30b96100b3cc332143acf7f309c96 (diff)
util: introduce typesafe_qsort(), a typesafe version of qsort()/qsort_safe()
It does two things: 1. It derives the element size from the array argument type 2. It derives the right type for the function from the array argument type Using this macro call should make the invocations of qsort() quite a bit safer.
-rw-r--r--src/basic/util.h8
1 files changed, 8 insertions, 0 deletions
diff --git a/src/basic/util.h b/src/basic/util.h
index 4a81243cc..825f04235 100644
--- a/src/basic/util.h
+++ b/src/basic/util.h
@@ -111,6 +111,14 @@ static inline void qsort_safe(void *base, size_t nmemb, size_t size, comparison_
qsort(base, nmemb, size, compar);
}
+/* A wrapper around the above, but that adds typesafety: the element size is automatically derived from the type and so
+ * is the prototype for the comparison function */
+#define typesafe_qsort(p, n, func) \
+ ({ \
+ int (*_func_)(const typeof(p[0])*, const typeof(p[0])*) = func; \
+ qsort_safe((p), (n), sizeof((p)[0]), (__compar_fn_t) _func_); \
+ })
+
/**
* Normal memcpy requires src to be nonnull. We do nothing if n is 0.
*/