Make jv_sort stable regardless of qsort details.
This commit is contained in:
1 parent
239c357af0
commit
7835a724d6
1 file changed
+4
-2
+4
-2
@@ -571,14 +571,15 @@ int jv_cmp(jv a, jv b) {
|
|||||||
struct sort_entry {
|
struct sort_entry {
|
||||||
jv object;
|
jv object;
|
||||||
jv key;
|
jv key;
|
||||||
|
int index;
|
||||||
};
|
};
|
||||||
|
|
||||||
static int sort_cmp(const void* pa, const void* pb) {
|
static int sort_cmp(const void* pa, const void* pb) {
|
||||||
const struct sort_entry* a = pa;
|
const struct sort_entry* a = pa;
|
||||||
const struct sort_entry* b = pb;
|
const struct sort_entry* b = pb;
|
||||||
int r = jv_cmp(jv_copy(a->key), jv_copy(b->key));
|
int r = jv_cmp(jv_copy(a->key), jv_copy(b->key));
|
||||||
// comparing by address if r == 0 makes the sort stable
|
// comparing by index if r == 0 makes the sort stable
|
||||||
return r ? r : (int)(a - b);
|
return r ? r : (a->index - b->index);
|
||||||
}
|
}
|
||||||
|
|
||||||
static struct sort_entry* sort_items(jv objects, jv keys) {
|
static struct sort_entry* sort_items(jv objects, jv keys) {
|
||||||
@@ -590,6 +591,7 @@ static struct sort_entry* sort_items(jv objects, jv keys) {
|
|||||||
for (int i=0; i<n; i++) {
|
for (int i=0; i<n; i++) {
|
||||||
entries[i].object = jv_array_get(jv_copy(objects), i);
|
entries[i].object = jv_array_get(jv_copy(objects), i);
|
||||||
entries[i].key = jv_array_get(jv_copy(keys), i);
|
entries[i].key = jv_array_get(jv_copy(keys), i);
|
||||||
|
entries[i].index = i;
|
||||||
}
|
}
|
||||||
jv_free(objects);
|
jv_free(objects);
|
||||||
jv_free(keys);
|
jv_free(keys);
|
||||||
|
|||||||
Reference in new issue
Block a user