1 /* Decode a message using oneof fields */
2 
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <pb_decode.h>
7 #include "oneof.pb.h"
8 #include "test_helpers.h"
9 #include "unittests.h"
10 
11 /* Test the 'AnonymousOneOfMessage' */
12 int test_oneof_1(pb_istream_t *stream, int option)
13 {
14     AnonymousOneOfMessage msg;
15     int status = 0;
16 
17     /* To better catch initialization errors */
18     memset(&msg, 0xAA, sizeof(msg));
19 
20     if (!pb_decode(stream, AnonymousOneOfMessage_fields, &msg))
21     {
22         printf("Decoding failed: %s\n", PB_GET_ERROR(stream));
23         return 1;
24     }
25 
26     /* Check that the basic fields work normally */
27     TEST(msg.prefix == 123);
28     TEST(msg.suffix == 321);
29 
30     /* Check that we got the right oneof according to command line */
31     if (option == 1)
32     {
33         TEST(msg.which_values == AnonymousOneOfMessage_first_tag);
34         TEST(msg.first == 999);
35     }
36     else if (option == 2)
37     {
38         TEST(msg.which_values == AnonymousOneOfMessage_second_tag);
39         TEST(strcmp(msg.second, "abcd") == 0);
40     }
41     else if (option == 3)
42     {
43         TEST(msg.which_values == AnonymousOneOfMessage_third_tag);
44         TEST(msg.third.array[0] == 1);
45         TEST(msg.third.array[1] == 2);
46         TEST(msg.third.array[2] == 3);
47         TEST(msg.third.array[3] == 4);
48         TEST(msg.third.array[4] == 5);
49     }
50 
51     return status;
52 }
53 
54 int main(int argc, char **argv)
55 {
56     uint8_t buffer[AnonymousOneOfMessage_size];
57     size_t count;
58     int option;
59 
60     if (argc != 2)
61     {
62         fprintf(stderr, "Usage: decode_oneof [number]\n");
63         return 1;
64     }
65     option = atoi(argv[1]);
66 
67     SET_BINARY_MODE(stdin);
68     count = fread(buffer, 1, sizeof(buffer), stdin);
69 
70     if (!feof(stdin))
71     {
72         printf("Message does not fit in buffer\n");
73         return 1;
74     }
75 
76     {
77         int status = 0;
78         pb_istream_t stream;
79 
80         stream = pb_istream_from_buffer(buffer, count);
81         status = test_oneof_1(&stream, option);
82 
83         if (status != 0)
84             return status;
85     }
86 
87     return 0;
88 }
89