Implement support for oneofs (C unions).
[apps/agl-service-can-low-level.git] / tests / oneof / decode_oneof.c
1 /* Decode a message using oneof fields */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <pb_decode.h>
6 #include "oneof.pb.h"
7 #include "test_helpers.h"
8 #include "unittests.h"
9
10 int main(int argc, char **argv)
11 {
12     uint8_t buffer[OneOfMessage_size];
13     OneOfMessage msg = OneOfMessage_init_zero;
14     pb_istream_t stream;
15     size_t count;
16     int option;
17
18     if (argc != 2)
19     {
20         fprintf(stderr, "Usage: encode_oneof [number]\n");
21         return 1;
22     }
23     option = atoi(argv[1]);
24
25     SET_BINARY_MODE(stdin);
26     count = fread(buffer, 1, sizeof(buffer), stdin);
27
28     if (!feof(stdin))
29     {
30         printf("Message does not fit in buffer\n");
31         return 1;
32     }
33
34     stream = pb_istream_from_buffer(buffer, count);
35
36     if (!pb_decode(&stream, OneOfMessage_fields, &msg))
37     {
38         printf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
39         return 1;
40     }
41
42     {
43         int status = 0;
44
45         /* Check that the basic fields work normally */
46         TEST(msg.prefix == 123);
47         TEST(msg.suffix == 321);
48
49         /* Check that we got the right oneof according to command line */
50         if (option == 1)
51         {
52             TEST(msg.which_values == OneOfMessage_first_tag);
53             TEST(msg.values.first == 999);
54         }
55         else if (option == 2)
56         {
57             TEST(msg.which_values == OneOfMessage_second_tag);
58             TEST(strcmp(msg.values.second, "abcd") == 0);
59         }
60         else if (option == 3)
61         {
62             TEST(msg.which_values == OneOfMessage_third_tag);
63             TEST(msg.values.third.array[0] == 1);
64             TEST(msg.values.third.array[1] == 2);
65             TEST(msg.values.third.array[2] == 3);
66             TEST(msg.values.third.array[3] == 4);
67             TEST(msg.values.third.array[4] == 5);
68         }
69
70         return status;
71     }
72 }