NanoCBOR icon indicating copy to clipboard operation
NanoCBOR copied to clipboard

No support for indefinite array

Open nagrawal63 opened this issue 5 years ago • 5 comments

The decoder given in the test/fuzz isn't able to decode an indefinite array encoded as: nanocbor_fmt_array_indefinite(enc); nanocbor_fmt_int(enc, 8); nanocbor_fmt_end_indefinite(enc);

nagrawal63 avatar Jan 31 '20 16:01 nagrawal63

Thanks for the issue, I've confirmed that there is indeed a problem. I'll try to provide a fix asap.

bergzand avatar Jan 31 '20 18:01 bergzand

I have done a small implementation for this to make it work for now. If you wish I can create a pull request.

nagrawal63 avatar Feb 03 '20 09:02 nagrawal63

I have done a small implementation for this to make it work for now. If you wish I can create a pull request.

I would appreciate that.

bergzand avatar Feb 06 '20 20:02 bergzand

Please find the code in PR #21 .

nagrawal63 avatar Feb 12 '20 15:02 nagrawal63

Same is true for indefinite maps

#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>

#include "nanocbor/nanocbor.h"

size_t _encode(uint8_t *buf, size_t len)
{
    nanocbor_encoder_t enc;
    nanocbor_encoder_init(&enc, buf, len);

    nanocbor_fmt_map_indefinite(&enc);
//  nanocbor_fmt_map(&enc, 2);

    /* write key - value pair*/
    nanocbor_fmt_uint(&enc, 0x1000);
    nanocbor_fmt_uint(&enc, 30);

    /* write key - value pair*/
    nanocbor_fmt_uint(&enc, 0x1001);
    nanocbor_fmt_uint(&enc, 60);

    nanocbor_fmt_end_indefinite(&enc);

    return nanocbor_encoded_len(&enc);
}

bool _decode(const uint8_t *buf, size_t len)
{
    nanocbor_value_t cfg, map;
    nanocbor_decoder_init(&cfg, buf, len);

    if (nanocbor_enter_map(&cfg, &map) < 0) {
        puts("can't enter map");
        return false;
    }

    while (!nanocbor_at_end(&map)) {
        uint32_t key, value;

        if (nanocbor_get_uint32(&map, &key) < 0) {
            puts("can't decode key");
            return false;
        }

        if (nanocbor_get_uint32(&map, &value) < 0) {
            puts("can't decode value");
            return false;
        }

        printf("%x: %d\n", key, value);
    }

    return true;
}

int main(void)
{
    uint8_t buffer[64];

    size_t len = _encode(buffer, sizeof(buffer));

    printf("encoded to %zd bytes\n", len);

    _decode(buffer, len);

    return 0;
}

Will print

encoded to 12 bytes can't enter map

with the indefinite version.

When using a definite map with two elements I get

encoded to 11 bytes 1000: 30 1001: 60

benpicco avatar Aug 17 '20 14:08 benpicco