| 1 |
#include "xh_config.h" |
| 2 |
#include "xh_core.h" |
| 3 |
|
| 4 |
static int |
| 5 |
xh_sort_hash_cmp(const void *p1, const void *p2) |
| 6 |
{ |
| 7 |
return xh_strcmp(((xh_sort_hash_t *) p1)->key, ((xh_sort_hash_t *) p2)->key); |
| 8 |
} |
| 9 |
|
| 10 |
xh_sort_hash_t * |
| 11 |
xh_sort_hash(HV *hash, size_t len) |
| 12 |
{ |
| 13 |
xh_sort_hash_t *sorted_hash; |
| 14 |
size_t i; |
| 15 |
|
| 16 |
sorted_hash = malloc(sizeof(xh_sort_hash_t) * len); |
| 17 |
if (sorted_hash == NULL) { |
| 18 |
croak("Memory allocation error"); |
| 19 |
} |
| 20 |
|
| 21 |
hv_iterinit(hash); |
| 22 |
|
| 23 |
for (i = 0; i < len; i++) { |
| 24 |
sorted_hash[i].value = hv_iternextsv(hash, (char **) &sorted_hash[i].key, &sorted_hash[i].key_len); |
| 25 |
} |
| 26 |
|
| 27 |
qsort(sorted_hash, len, sizeof(xh_sort_hash_t), xh_sort_hash_cmp); |
| 28 |
|
| 29 |
return sorted_hash; |
| 30 |
} |
| 31 |
|
| 32 |
/* Callers register this with SAVEDESTRUCTOR_X so that the sorted hash is |
| 33 |
* released both on the normal path and when a perl callback dies in the |
| 34 |
* middle of the loop and longjmps past the end of the block. */ |
| 35 |
void |
| 36 |
xh_sort_hash_free(pTHX_ void *sorted_hash) |
| 37 |
{ |
| 38 |
PERL_UNUSED_CONTEXT; |
| 39 |
free(sorted_hash); |
| 40 |
} |