1058aa793SEd Maste /*
2058aa793SEd Maste * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
3058aa793SEd Maste *
4058aa793SEd Maste * libcbor is free software; you can redistribute it and/or modify
5058aa793SEd Maste * it under the terms of the MIT license. See LICENSE for details.
6058aa793SEd Maste */
7058aa793SEd Maste
8058aa793SEd Maste #include <stdlib.h>
9058aa793SEd Maste #include "cbor.h"
10058aa793SEd Maste
usage(void)11058aa793SEd Maste void usage(void) {
12058aa793SEd Maste printf("Usage: streaming_array <N>\n");
13058aa793SEd Maste printf("Prints out serialized array [0, ..., N-1]\n");
14058aa793SEd Maste exit(1);
15058aa793SEd Maste }
16058aa793SEd Maste
17058aa793SEd Maste #define BUFFER_SIZE 8
18058aa793SEd Maste unsigned char buffer[BUFFER_SIZE];
19058aa793SEd Maste FILE* out;
20058aa793SEd Maste
flush(size_t bytes)21058aa793SEd Maste void flush(size_t bytes) {
22058aa793SEd Maste if (bytes == 0) exit(1); // All items should be successfully encoded
23058aa793SEd Maste if (fwrite(buffer, sizeof(unsigned char), bytes, out) != bytes) exit(1);
24058aa793SEd Maste if (fflush(out)) exit(1);
25058aa793SEd Maste }
26058aa793SEd Maste
27058aa793SEd Maste /*
28058aa793SEd Maste * Example of using the streaming encoding API to create an array of integers
29058aa793SEd Maste * on the fly. Notice that a partial output is produced with every element.
30058aa793SEd Maste */
main(int argc,char * argv[])31058aa793SEd Maste int main(int argc, char* argv[]) {
32058aa793SEd Maste if (argc != 2) usage();
33058aa793SEd Maste long n = strtol(argv[1], NULL, 10);
34058aa793SEd Maste out = freopen(NULL, "wb", stdout);
35058aa793SEd Maste if (!out) exit(1);
36058aa793SEd Maste
37058aa793SEd Maste // Start an indefinite-length array
38058aa793SEd Maste flush(cbor_encode_indef_array_start(buffer, BUFFER_SIZE));
39058aa793SEd Maste // Write the array items one by one
40058aa793SEd Maste for (size_t i = 0; i < n; i++) {
41058aa793SEd Maste flush(cbor_encode_uint32(i, buffer, BUFFER_SIZE));
42058aa793SEd Maste }
43058aa793SEd Maste // Close the array
44058aa793SEd Maste flush(cbor_encode_break(buffer, BUFFER_SIZE));
45058aa793SEd Maste
46058aa793SEd Maste if (fclose(out)) exit(1);
47058aa793SEd Maste }
48