1 /* This program takes a command line argument and encodes a message in
2 * one of MsgType1, MsgType2 or MsgType3.
10 #include "unionproto.pb.h"
12 /* This function is the core of the union encoding process. It handles
13 * the top-level pb_field_t array manually, in order to encode a correct
14 * field tag before the message. The pointer to MsgType_fields array is
15 * used as an unique identifier for the message type.
17 bool encode_unionmessage(pb_ostream_t *stream, const pb_field_t messagetype[], const void *message)
19 const pb_field_t *field;
20 for (field = UnionMessage_fields; field->tag != 0; field++)
22 if (field->ptr == messagetype)
24 /* This is our field, encode the message using it. */
25 if (!pb_encode_tag_for_field(stream, field))
28 return pb_encode_submessage(stream, messagetype, message);
32 /* Didn't find the field for messagetype */
36 int main(int argc, char **argv)
40 fprintf(stderr, "Usage: %s (1|2|3)\n", argv[0]);
45 pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
48 int msgtype = atoi(argv[1]);
51 /* Send message of type 1 */
53 status = encode_unionmessage(&stream, MsgType1_fields, &msg);
55 else if (msgtype == 2)
57 /* Send message of type 2 */
58 MsgType2 msg = {true};
59 status = encode_unionmessage(&stream, MsgType2_fields, &msg);
61 else if (msgtype == 3)
63 /* Send message of type 3 */
64 MsgType3 msg = {3, 1415};
65 status = encode_unionmessage(&stream, MsgType3_fields, &msg);
69 fprintf(stderr, "Unknown message type: %d\n", msgtype);
75 fprintf(stderr, "Encoding failed!\n");
80 fwrite(buffer, 1, stream.bytes_written, stdout);
81 return 0; /* Success */