Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Date: Sun, 8 Aug 2021 13:42:27 +0100
From: Jon Chesterfield <>
Cc: Olivier Galibert <>
Subject: Re: [PATCH] stdlib: implement qsort_r

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

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*

// 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!


Content of type "text/html" skipped

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.