1*5d3e7166SEd Maste /*
2*5d3e7166SEd Maste * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
3*5d3e7166SEd Maste *
4*5d3e7166SEd Maste * libcbor is free software; you can redistribute it and/or modify
5*5d3e7166SEd Maste * it under the terms of the MIT license. See LICENSE for details.
6*5d3e7166SEd Maste */
7*5d3e7166SEd Maste
8*5d3e7166SEd Maste #include <stdlib.h>
9*5d3e7166SEd Maste #include "cbor.h"
10*5d3e7166SEd Maste
usage(void)11*5d3e7166SEd Maste void usage(void) {
12*5d3e7166SEd Maste printf("Usage: streaming_array <N>\n");
13*5d3e7166SEd Maste printf("Prints out serialized array [0, ..., N-1]\n");
14*5d3e7166SEd Maste exit(1);
15*5d3e7166SEd Maste }
16*5d3e7166SEd Maste
17*5d3e7166SEd Maste #define BUFFER_SIZE 8
18*5d3e7166SEd Maste unsigned char buffer[BUFFER_SIZE];
19*5d3e7166SEd Maste FILE* out;
20*5d3e7166SEd Maste
flush(size_t bytes)21*5d3e7166SEd Maste void flush(size_t bytes) {
22*5d3e7166SEd Maste if (bytes == 0) exit(1); // All items should be successfully encoded
23*5d3e7166SEd Maste if (fwrite(buffer, sizeof(unsigned char), bytes, out) != bytes) exit(1);
24*5d3e7166SEd Maste if (fflush(out)) exit(1);
25*5d3e7166SEd Maste }
26*5d3e7166SEd Maste
27*5d3e7166SEd Maste /*
28*5d3e7166SEd Maste * Example of using the streaming encoding API to create an array of integers
29*5d3e7166SEd Maste * on the fly. Notice that a partial output is produced with every element.
30*5d3e7166SEd Maste */
main(int argc,char * argv[])31*5d3e7166SEd Maste int main(int argc, char* argv[]) {
32*5d3e7166SEd Maste if (argc != 2) usage();
33*5d3e7166SEd Maste long n = strtol(argv[1], NULL, 10);
34*5d3e7166SEd Maste out = freopen(NULL, "wb", stdout);
35*5d3e7166SEd Maste if (!out) exit(1);
36*5d3e7166SEd Maste
37*5d3e7166SEd Maste // Start an indefinite-length array
38*5d3e7166SEd Maste flush(cbor_encode_indef_array_start(buffer, BUFFER_SIZE));
39*5d3e7166SEd Maste // Write the array items one by one
40*5d3e7166SEd Maste for (size_t i = 0; i < n; i++) {
41*5d3e7166SEd Maste flush(cbor_encode_uint32(i, buffer, BUFFER_SIZE));
42*5d3e7166SEd Maste }
43*5d3e7166SEd Maste // Close the array
44*5d3e7166SEd Maste flush(cbor_encode_break(buffer, BUFFER_SIZE));
45*5d3e7166SEd Maste
46*5d3e7166SEd Maste if (fclose(out)) exit(1);
47*5d3e7166SEd Maste }
48