1 /* Encode a message using oneof fields */
2 
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <pb_encode.h>
6 #include "oneof.pb.h"
7 #include "test_helpers.h"
8 
9 int main(int argc, char **argv)
10 {
11     uint8_t buffer[OneOfMessage_size];
12     OneOfMessage msg = OneOfMessage_init_zero;
13     pb_ostream_t stream;
14     int option;
15 
16     if (argc != 2)
17     {
18         fprintf(stderr, "Usage: encode_oneof [number]\n");
19         return 1;
20     }
21     option = atoi(argv[1]);
22 
23     /* Prefix and suffix are used to test that the union does not disturb
24      * other fields in the same message. */
25     msg.prefix = 123;
26 
27     /* We encode one of the 'values' fields based on command line argument */
28     if (option == 1)
29     {
30         msg.which_values = OneOfMessage_first_tag;
31         msg.values.first = 999;
32     }
33     else if (option == 2)
34     {
35         msg.which_values = OneOfMessage_second_tag;
36         strcpy(msg.values.second, "abcd");
37     }
38     else if (option == 3)
39     {
40         msg.which_values = OneOfMessage_third_tag;
41         msg.values.third.array_count = 5;
42         msg.values.third.array[0] = 1;
43         msg.values.third.array[1] = 2;
44         msg.values.third.array[2] = 3;
45         msg.values.third.array[3] = 4;
46         msg.values.third.array[4] = 5;
47     }
48 
49     msg.suffix = 321;
50 
51     stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
52 
53     if (pb_encode(&stream, OneOfMessage_fields, &msg))
54     {
55         SET_BINARY_MODE(stdout);
56         fwrite(buffer, 1, stream.bytes_written, stdout);
57         return 0;
58     }
59     else
60     {
61         fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
62         return 1;
63     }
64 }
65