Decode repeated uint32

548 views
Skip to first unread message

Idan Noti

unread,
Jul 22, 2014, 4:32:37 AM7/22/14
to nan...@googlegroups.com
Hi,
I have the following message:
message M1
{
    repeated uint32 field1  
= 1;
}

This is the encoder callback:
bool encode_numbers_list(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
{
    uint32_t numbers[2] = {2, 11};
    int iterator;
    for (iterator = 0; iterator < 2; iterator++)
    {
        if (!pb_encode_tag_for_field(stream, field))
            return false;
        
        if (!pb_encode_varint(stream, numbers[iterator]))
            return false;
    }
    return true;
}

As you can see, all the numbers are encoded in a single callback.

I tried to achieve the same when decoding, but I can only decode single number per callback.
This is currently my decoder callback:
bool parse_single_number(pb_istream_t *stream, const pb_field_t *field, void **arg)
{
    uint64_t value;

    if (!pb_decode_varint(stream, &value))
        return false;
    
    printf("number = %d\n", (uint32_t)value);

    return true;
}

I would rather have something like this:
bool parse_all_numbers(pb_istream_t *stream, const pb_field_t *field, void **arg)
{
    uint64_t value;

    while (stream->bytes_left)
    {
        if (!pb_decode_varint(stream, &value))
return false;
printf("number = %d\n", (uint32_t)value);
    }

    return true;
}


in which bytes_left will include all the numbers.

Is it possible somehow?

Thanks

Petteri Aimonen

unread,
Jul 22, 2014, 5:06:49 AM7/22/14
to nan...@googlegroups.com
Hi,

> As you can see, *all *the numbers are encoded in a single callback.
> I tried to achieve the same when decoding, but I can only decode single
> number per callback.

Yes, this is normal.

Protocol buffers format allows the fields to arrive in any order, so
there can be other data between repeated fields. Of course this is
usually not the case, but is allowed by the specs.

If the field is packed, then you can read multiple values in decoding
callback. This is a good thing from efficiency standpoint, but your
callback must still be able to handle separated data.

(You can also modify your encoding callback to write data in packed
format. Look at
https://code.google.com/p/nanopb/source/browse/pb_encode.c#124 for an
example.)

--
Petteri

Idan Noti

unread,
Jul 22, 2014, 5:48:11 AM7/22/14
to nan...@googlegroups.com
Hi,
You wrote:
If the field is packed, then you can read multiple values in decoding 
callback.
How is it done? Does it require special decoding methods?

Thanks

Petteri Aimonen

unread,
Jul 22, 2014, 5:54:24 AM7/22/14
to nan...@googlegroups.com
Hi,

> How is it done? Does it require special decoding methods?

Exactly like your parse_all_numbers() does it.

If the callback does not read all of the stream, it will just be called
again until it does.

--
Petteri
Reply all
Reply to author
Forward
0 new messages