1 #include "submsg_callback.pb.h"
2 #include <pb_encode.h>
3 #include <pb_decode.h>
4 #include "unittests.h"
5 
msg_callback(pb_istream_t * stream,const pb_field_t * field,void ** arg)6 bool msg_callback(pb_istream_t *stream, const pb_field_t *field, void **arg)
7 {
8     /* This tests decoding the submessage already in the message level callback. */
9 
10     SubMessage *submsg = (SubMessage*)field->pData;
11 
12     if (!pb_decode(stream, SubMessage_fields, submsg))
13         PB_RETURN_ERROR(stream, "submsg decode failed");
14 
15     if (submsg->foo != 1234)
16         PB_RETURN_ERROR(stream, "submsg.foo wrong value");
17 
18     return true;
19 }
20 
main()21 int main()
22 {
23     int status = 0;
24     pb_byte_t buf[64];
25     size_t msglen;
26 
27     {
28         pb_ostream_t ostream = pb_ostream_from_buffer(buf, sizeof(buf));
29         MyMessage msg = MyMessage_init_zero;
30 
31         msg.which_oneof = MyMessage_submsg_tag;
32         msg.oneof.submsg.foo = 1234;
33 
34         if (!pb_encode(&ostream, MyMessage_fields, &msg))
35         {
36             fprintf(stderr, "pb_encode() failed: %s\n", PB_GET_ERROR(&ostream));
37             return 1;
38         }
39 
40         msglen = ostream.bytes_written;
41         TEST(msglen > 0);
42     }
43 
44     {
45         pb_istream_t istream = pb_istream_from_buffer(buf, msglen);
46         MyMessage msg = MyMessage_init_zero;
47         msg.cb_oneof.funcs.decode = msg_callback;
48 
49         if (!pb_decode(&istream, MyMessage_fields, &msg))
50         {
51             fprintf(stderr, "pb_decode() failed: %s\n", PB_GET_ERROR(&istream));
52             return 1;
53         }
54     }
55 
56     return status;
57 }