| 1 |
/// @file |
| 2 |
/// @brief `qsort` with carried along context |
| 3 |
/// @ingroup cgraph_utils |
| 4 |
/// |
| 5 |
/// The non-standard `qsort_r`, Windows’ `qsort_s`, and C11’s `qsort_s` provide |
| 6 |
/// a `qsort` alternative with an extra state parameter. Unfortunately none of |
| 7 |
/// these are easily usable portably in Graphviz. This header implements an |
| 8 |
/// alternative that hopefully is. |
| 9 |
|
| 10 |
#pragma once |
| 11 |
|
| 12 |
#include <assert.h> |
| 13 |
#include <stdlib.h> |
| 14 |
|
| 15 |
static _Thread_local int (*gv_sort_compar)(const void *, const void *, void *); |
| 16 |
static _Thread_local void *gv_sort_arg; |
| 17 |
|
| 18 |
static inline int gv_sort_compar_wrapper(const void *a, const void *b) { |
| 19 |
assert(gv_sort_compar != NULL && "no comparator set in gv_sort"); |
| 20 |
return gv_sort_compar(a, b, gv_sort_arg); |
| 21 |
} |
| 22 |
|
| 23 |
/// `qsort` with an extra state parameter, ala `qsort_r` |
| 24 |
static inline void gv_sort(void *base, size_t nmemb, size_t size, |
| 25 |
int (*compar)(const void *, const void *, void *), |
| 26 |
void *arg) { |
| 27 |
assert(gv_sort_compar == NULL && gv_sort_arg == NULL && |
| 28 |
"unsupported recursive call to gv_sort"); |
| 29 |
|
| 30 |
gv_sort_compar = compar; |
| 31 |
gv_sort_arg = arg; |
| 32 |
|
| 33 |
if (nmemb > 1) { |
| 34 |
qsort(base, nmemb, size, gv_sort_compar_wrapper); |
| 35 |
} |
| 36 |
|
| 37 |
gv_sort_compar = NULL; |
| 38 |
gv_sort_arg = NULL; |
| 39 |
} |