jv jv_array() { return jv_array_sized(16); }
int minlen = lena < lenb ? lena : lenb; int r = memcmp(jv_string_value(*a), jv_string_value(*b), minlen); if (r == 0) r = lena - lenb; return r; } static void f_keys(jv input[], jv output[]) { if (jv_get_kind(input[0]) == JV_KIND_OBJECT) { int nkeys = jv_object_length(jv_copy(input[0])); jv* keys = malloc(sizeof(jv) * nkeys); int kidx = 0; jv_object_foreach(i, input[0]) { keys[kidx++] = jv_object_iter_key(input[0], i); } qsort(keys, nkeys, sizeof(jv), string_cmp); output[0] = jv_array_sized(nkeys); for (int i = 0; i<nkeys; i++) { output[0] = jv_array_append(output[0], keys[i]); } free(keys); jv_free(input[0]); } else if (jv_get_kind(input[0]) == JV_KIND_ARRAY) { int n = jv_array_length(input[0]); output[0] = jv_array(); for (int i=0; i<n; i++){ output[0] = jv_array_set(output[0], i, jv_number(i)); } } else { output[0] = jv_invalid_with_msg(jv_string_fmt("'keys' only supports object, not %s", jv_kind_name(jv_get_kind(input[0])))); jv_free(input[0]);
int minlen = lena < lenb ? lena : lenb; int r = memcmp(jv_string_value(*a), jv_string_value(*b), minlen); if (r == 0) r = lena - lenb; return r; } jv jv_keys(jv x) { if (jv_get_kind(x) == JV_KIND_OBJECT) { int nkeys = jv_object_length(jv_copy(x)); jv* keys = malloc(sizeof(jv) * nkeys); int kidx = 0; jv_object_foreach(i, x) { keys[kidx++] = jv_object_iter_key(x, i); } qsort(keys, nkeys, sizeof(jv), string_cmp); jv answer = jv_array_sized(nkeys); for (int i = 0; i<nkeys; i++) { answer = jv_array_append(answer, keys[i]); } free(keys); jv_free(x); return answer; } else if (jv_get_kind(x) == JV_KIND_ARRAY) { int n = jv_array_length(x); jv answer = jv_array(); for (int i=0; i<n; i++){ answer = jv_array_set(answer, i, jv_number(i)); } return answer; } else { assert(0 && "jv_keys passed something neither object nor array");