Handle unsupported extension field types more gracefully.
[apps/agl-service-can-low-level.git] / tests / basic_stream / decode_stream.c
1 /* Same as test_decode1 but reads from stdin directly.
2  */
3
4 #include <stdio.h>
5 #include <pb_decode.h>
6 #include "person.pb.h"
7
8 /* This function is called once from main(), it handles
9    the decoding and printing.
10    Ugly copy-paste from test_decode1.c. */
11 bool print_person(pb_istream_t *stream)
12 {
13     int i;
14     Person person;
15     
16     if (!pb_decode(stream, Person_fields, &person))
17         return false;
18     
19     /* Now the decoding is done, rest is just to print stuff out. */
20
21     printf("name: \"%s\"\n", person.name);
22     printf("id: %ld\n", (long)person.id);
23     
24     if (person.has_email)
25         printf("email: \"%s\"\n", person.email);
26     
27     for (i = 0; i < person.phone_count; i++)
28     {
29         Person_PhoneNumber *phone = &person.phone[i];
30         printf("phone {\n");
31         printf("  number: \"%s\"\n", phone->number);
32         
33         if (phone->has_type)
34         {
35             switch (phone->type)
36             {
37                 case Person_PhoneType_WORK:
38                     printf("  type: WORK\n");
39                     break;
40                 
41                 case Person_PhoneType_HOME:
42                     printf("  type: HOME\n");
43                     break;
44                 
45                 case Person_PhoneType_MOBILE:
46                     printf("  type: MOBILE\n");
47                     break;
48             }
49         }
50         printf("}\n");
51     }
52     
53     return true;
54 }
55
56 /* This binds the pb_istream_t to stdin */
57 bool callback(pb_istream_t *stream, uint8_t *buf, size_t count)
58 {
59     FILE *file = (FILE*)stream->state;
60     bool status;
61     
62     status = (fread(buf, 1, count, file) == count);
63     
64     if (feof(file))
65         stream->bytes_left = 0;
66     
67     return status;
68 }
69
70 int main()
71 {
72     /* Maximum size is specified to prevent infinite length messages from
73      * hanging this in the fuzz test.
74      */
75     pb_istream_t stream = {&callback, stdin, 10000};
76     if (!print_person(&stream))
77     {
78         printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
79         return 1;
80     } else {
81         return 0;
82     }
83 }