Bob
Bob

Reputation: 4970

nanopb pb_istream_from_buffer - what is value of bufsize?

pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize);

buf - Pointer to byte array to read from.
bufsize Size of the byte array.

What is the argument for bufsize? Is it the macro in the .pb.h file under the heading /* Maximum encoded size of messages (where known) */?

The example in simple.c is slightly confusing because it uses the buffer that it created for the output example.

My payload can be up to 2048 and the encoded maximum is 2051; which one do I pass in as size_t bufsize?

Upvotes: 0

Views: 469

Answers (2)

karstenmtr
karstenmtr

Reputation: 26

My solution is to determine the message length from the buffer before calling pb_istream_from_buffer().

long protobuf_message_len(void *buf, long offset, unsigned long len)
{
    long start = offset;
    unsigned long long value;
    while(offset<=len)
    {
        offset = protobuf_read_varint(&value,buf,offset);
        if (value == 0)
            return offset-start-1;
        switch (value & 0x07)
        {
            case 0:
                offset = protobuf_read_varint(&value,buf,offset);
                break;
            case 1:
                offset += 8;
                break;
            case 2:
                offset = protobuf_read_varint(&value,buf,offset);
                offset += value;
                break;
            case 5:
                offset += 4;
                break;
            default:
                return -2;
        }
    }
    return -1;
}

unsigned long protobuf_read_varint(unsigned long long *value, void *buf, long offset)
{
    unsigned short i = 0;
    char byte;
    *value = 0;
    while (1) {
        offset = protobuf_read_byte(&byte, buf, offset);
        *value |= (unsigned long long)(byte & 0x7F) << i*7;
        i++;
        if ((byte & 0x80) == 0) {
            return offset;
        }
    }
    return 0;
}

long protobuf_read_byte(char *value, void *buf, long offset)
{
    *value = *((char *) buf + offset);
    return ++offset;
}

Upvotes: 0

jpa
jpa

Reputation: 12156

It is the actual length of the message to be decoded. Protobuf messages do not have any terminator themselves, so the length of the message data must be passed to the decoder.

Upvotes: 0

Related Questions