1 #include "test.pb.h"
2 #include <unittests.h>
3 #include <pb_encode.h>
4 #include <pb_decode.h>
5 
write_array(pb_ostream_t * stream,const pb_field_t * field,void * const * arg)6 static bool write_array(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
7 {
8     int i;
9     for (i = 0; i < 5; i++)
10     {
11         if (!pb_encode_tag_for_field(stream, field))
12             return false;
13         if (!pb_encode_varint(stream, 1000 + i))
14             return false;
15     }
16 
17     return true;
18 }
19 
read_array(pb_istream_t * stream,const pb_field_t * field,void ** arg)20 static bool read_array(pb_istream_t *stream, const pb_field_t *field, void **arg)
21 {
22     uint32_t i;
23     int *sum = *arg;
24 
25     if (!pb_decode_varint32(stream, &i))
26         return false;
27 
28     *sum += i;
29 
30     return true;
31 }
32 
main()33 int main()
34 {
35     int status = 0;
36     pb_byte_t buf[128] = {0};
37     pb_size_t msglen;
38 
39     {
40         MainMessage msg = MainMessage_init_zero;
41         pb_ostream_t stream = pb_ostream_from_buffer(buf, sizeof(buf));
42         msg.submsg.foo.funcs.encode = &write_array;
43         TEST(pb_encode(&stream, MainMessage_fields, &msg));
44         msglen = stream.bytes_written;
45     }
46 
47     {
48         MainMessage msg = MainMessage_init_zero;
49         pb_istream_t stream = pb_istream_from_buffer(buf, msglen);
50         int sum = 0;
51         msg.submsg.foo.funcs.decode = &read_array;
52         msg.submsg.foo.arg = &sum;
53         TEST(pb_decode(&stream, MainMessage_fields, &msg));
54         TEST(sum == 1000 + 1001 + 1002 + 1003 + 1004);
55     }
56 
57     return status;
58 }
59 
60