Path: blob/main/contrib/libcbor/examples/streaming_parser.c
39586 views
/*1* Copyright (c) 2014-2020 Pavel Kalvoda <[email protected]>2*3* libcbor is free software; you can redistribute it and/or modify4* it under the terms of the MIT license. See LICENSE for details.5*/67#include <stdio.h>8#include <string.h>9#include "cbor.h"1011#ifdef __GNUC__12#define UNUSED(x) __attribute__((__unused__)) x13#else14#define UNUSED(x) x15#endif1617void usage(void) {18printf("Usage: streaming_parser [input file]\n");19exit(1);20}2122/*23* Illustrates how one might skim through a map (which is assumed to have24* string keys and values only), looking for the value of a specific key25*26* Use the examples/data/map.cbor input to test this.27*/2829const char* key = "a secret key";30bool key_found = false;3132void find_string(void* UNUSED(_ctx), cbor_data buffer, uint64_t len) {33if (key_found) {34printf("Found the value: %.*s\n", (int)len, buffer);35key_found = false;36} else if (len == strlen(key)) {37key_found = (memcmp(key, buffer, len) == 0);38}39}4041int main(int argc, char* argv[]) {42if (argc != 2) usage();43FILE* f = fopen(argv[1], "rb");44if (f == NULL) usage();45fseek(f, 0, SEEK_END);46size_t length = (size_t)ftell(f);47fseek(f, 0, SEEK_SET);48unsigned char* buffer = malloc(length);49fread(buffer, length, 1, f);5051struct cbor_callbacks callbacks = cbor_empty_callbacks;52struct cbor_decoder_result decode_result;53size_t bytes_read = 0;54callbacks.string = find_string;55while (bytes_read < length) {56decode_result = cbor_stream_decode(buffer + bytes_read, length - bytes_read,57&callbacks, NULL);58bytes_read += decode_result.read;59}6061free(buffer);62fclose(f);63}646566