chiark / gitweb /
util: introduce typesafe_qsort(), a typesafe version of qsort()/qsort_safe()
authorLennart Poettering <lennart@poettering.net>
Tue, 27 Mar 2018 12:56:29 +0000 (14:56 +0200)
committerSven Eden <yamakuzure@gmx.net>
Fri, 24 Aug 2018 14:47:08 +0000 (16:47 +0200)
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.

src/basic/util.h

index 4a81243cc0c07e56fb288cdea100172cb95cc47a..825f04235e1bf35748267e9cc57dbc75d2d08f62 100644 (file)
@@ -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.
  */