xref: /freebsd/contrib/libcbor/examples/sort.c (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
1 /*
2  * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
3  *
4  * libcbor is free software; you can redistribute it and/or modify
5  * it under the terms of the MIT license. See LICENSE for details.
6  */
7 
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include "cbor.h"
11 
12 /*
13  * Illustrates how to use the contiguous storage of nested items with
14  * standard library functions.
15  */
16 
17 int comparUint(const void *a, const void *b) {
18   uint8_t av = cbor_get_uint8(*(cbor_item_t **)a),
19           bv = cbor_get_uint8(*(cbor_item_t **)b);
20 
21   if (av < bv)
22     return -1;
23   else if (av == bv)
24     return 0;
25   else
26     return 1;
27 }
28 
29 int main(int argc, char *argv[]) {
30   cbor_item_t *array = cbor_new_definite_array(4);
31   cbor_array_push(array, cbor_move(cbor_build_uint8(4)));
32   cbor_array_push(array, cbor_move(cbor_build_uint8(3)));
33   cbor_array_push(array, cbor_move(cbor_build_uint8(1)));
34   cbor_array_push(array, cbor_move(cbor_build_uint8(2)));
35 
36   qsort(cbor_array_handle(array), cbor_array_size(array), sizeof(cbor_item_t *),
37         comparUint);
38 
39   cbor_describe(array, stdout);
40   fflush(stdout);
41 }
42