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 <stdlib.h>
9#include "cbor.h"
10
11void usage(void) {
12  printf("Usage: streaming_array <N>\n");
13  printf("Prints out serialized array [0, ..., N-1]\n");
14  exit(1);
15}
16
17#define BUFFER_SIZE 8
18unsigned char buffer[BUFFER_SIZE];
19FILE* out;
20
21void flush(size_t bytes) {
22  if (bytes == 0) exit(1);  // All items should be successfully encoded
23  if (fwrite(buffer, sizeof(unsigned char), bytes, out) != bytes) exit(1);
24  if (fflush(out)) exit(1);
25}
26
27/*
28 * Example of using the streaming encoding API to create an array of integers
29 * on the fly. Notice that a partial output is produced with every element.
30 */
31int main(int argc, char* argv[]) {
32  if (argc != 2) usage();
33  long n = strtol(argv[1], NULL, 10);
34  out = freopen(NULL, "wb", stdout);
35  if (!out) exit(1);
36
37  // Start an indefinite-length array
38  flush(cbor_encode_indef_array_start(buffer, BUFFER_SIZE));
39  // Write the array items one by one
40  for (size_t i = 0; i < n; i++) {
41    flush(cbor_encode_uint32(i, buffer, BUFFER_SIZE));
42  }
43  // Close the array
44  flush(cbor_encode_break(buffer, BUFFER_SIZE));
45
46  if (fclose(out)) exit(1);
47}
48