I don’t believe in deep inlining in that case, there’s too much recursion. As for adding overhead to qsort by sharing qsort_r’s code it is indeed trivial to do but I don’t know whether the tradeoff should be done. OG. Le dim. 8 août 2021 à 14:42, Jon Chesterfield < jonathanchesterfield@gmail.com> a écrit : > On Sun, Aug 8, 2021 at 12:29 PM Olivier Galibert > wrote: > >> The extension qsort_r allows calling qsort on a list of indices >> without having a global variable to hold the data to sort. >> > > qsort_r is a strong improvement on qsort. I think it's available outside of > glibc. > > I remember doing something similar locally. Just looked it up and I > renamed & mutated qsort to pass the context along. Therefore typed into > email, I think something like this would provide an implementation of > qsort in terms of qsort_r. > > // declare qsort_r > typedef int (*cmp_r_t)(const void *, const void *, void * context); > > > void qsort_r(void *base, size_t nel, size_t width, cmp_r_t cmp, void* > context); > > > // pass it a function that extracts the comparator for qsort from the > // context > typedef int (*cmp_t)(const void *, const void *); > > > static int compare_adapter(const void *l, const void *r, void * context) > { > cmpt_t c = (cmpt_t) context; > > > return c(l,r); > > > } > > // tail call > void qsort(void *base, size_t nel, size_t width, cmp_t c) > { > return qsort_r(base, nel, width, compare_adapter, (cmp_t_t)c); > > > } > > Given optimism about inlining or an always inline annotation > it should turn into the same machine code as the macro > instantiation approach. Alternatively it's a tail call into qsort_r, so > a couple of indirections in exchange for minimal code size growth. > > I haven't compiled or tested that (or looked up the coding conventions > for musl) so this is a drive by suggestion, written in pseudocode > instead of prose for clarity. > > Thanks all! > > Jon > >