xref: /freebsd/contrib/libcbor/examples/sort.c (revision 5d3e7166f6a0187fa3f8831b16a06bd9955c21ff)
110ff414cSEd Maste /*
210ff414cSEd Maste  * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
310ff414cSEd Maste  *
410ff414cSEd Maste  * libcbor is free software; you can redistribute it and/or modify
510ff414cSEd Maste  * it under the terms of the MIT license. See LICENSE for details.
610ff414cSEd Maste  */
710ff414cSEd Maste 
810ff414cSEd Maste #include <stdio.h>
910ff414cSEd Maste #include <stdlib.h>
1010ff414cSEd Maste #include "cbor.h"
1110ff414cSEd Maste 
1210ff414cSEd Maste /*
1310ff414cSEd Maste  * Illustrates how to use the contiguous storage of nested items with
1410ff414cSEd Maste  * standard library functions.
1510ff414cSEd Maste  */
1610ff414cSEd Maste 
compareUint(const void * a,const void * b)17*5d3e7166SEd Maste int compareUint(const void *a, const void *b) {
1810ff414cSEd Maste   uint8_t av = cbor_get_uint8(*(cbor_item_t **)a),
1910ff414cSEd Maste           bv = cbor_get_uint8(*(cbor_item_t **)b);
2010ff414cSEd Maste 
2110ff414cSEd Maste   if (av < bv)
2210ff414cSEd Maste     return -1;
2310ff414cSEd Maste   else if (av == bv)
2410ff414cSEd Maste     return 0;
2510ff414cSEd Maste   else
2610ff414cSEd Maste     return 1;
2710ff414cSEd Maste }
2810ff414cSEd Maste 
main(void)29*5d3e7166SEd Maste int main(void) {
3010ff414cSEd Maste   cbor_item_t *array = cbor_new_definite_array(4);
31*5d3e7166SEd Maste   bool success = cbor_array_push(array, cbor_move(cbor_build_uint8(4)));
32*5d3e7166SEd Maste   success &= cbor_array_push(array, cbor_move(cbor_build_uint8(3)));
33*5d3e7166SEd Maste   success &= cbor_array_push(array, cbor_move(cbor_build_uint8(1)));
34*5d3e7166SEd Maste   success &= cbor_array_push(array, cbor_move(cbor_build_uint8(2)));
35*5d3e7166SEd Maste   if (!success) return 1;
3610ff414cSEd Maste 
3710ff414cSEd Maste   qsort(cbor_array_handle(array), cbor_array_size(array), sizeof(cbor_item_t *),
38*5d3e7166SEd Maste         compareUint);
3910ff414cSEd Maste 
4010ff414cSEd Maste   cbor_describe(array, stdout);
4110ff414cSEd Maste   fflush(stdout);
4210ff414cSEd Maste }
43