3b72f6644349c9568985f3a806a432599942b60d
[apps/agl-service-can-low-level.git] / tests / test_decode1.c
1 /* A very simple decoding test case, using person.proto.
2  * Produces output compatible with protoc --decode.
3  * Reads the encoded data from stdin and prints the values
4  * to stdout as text.
5  *
6  * Run e.g. ./test_encode1 | ./test_decode1
7  */
8
9 #include <stdio.h>
10 #include <pb_decode.h>
11 #include "person.pb.h"
12
13 /* This function is called once from main(), it handles
14    the decoding and printing. */
15 bool print_person(pb_istream_t *stream)
16 {
17     int i;
18     Person person;
19     
20     if (!pb_decode(stream, Person_fields, &person))
21         return false;
22     
23     /* Now the decoding is done, rest is just to print stuff out. */
24
25     printf("name: \"%s\"\n", person.name);
26     printf("id: %ld\n", (long)person.id);
27     
28     if (person.has_email)
29         printf("email: \"%s\"\n", person.email);
30     
31     for (i = 0; i < person.phone_count; i++)
32     {
33         Person_PhoneNumber *phone = &person.phone[i];
34         printf("phone {\n");
35         printf("  number: \"%s\"\n", phone->number);
36         
37         if (phone->has_type)
38         {
39             switch (phone->type)
40             {
41                 case Person_PhoneType_WORK:
42                     printf("  type: WORK\n");
43                     break;
44                 
45                 case Person_PhoneType_HOME:
46                     printf("  type: HOME\n");
47                     break;
48                 
49                 case Person_PhoneType_MOBILE:
50                     printf("  type: MOBILE\n");
51                     break;
52             }
53         }
54         printf("}\n");
55     }
56     
57     return true;
58 }
59
60 /* This binds the pb_istream_t to stdin */
61 bool callback(pb_istream_t *stream, uint8_t *buf, size_t count)
62 {
63     FILE *file = (FILE*)stream->state;
64     bool status;
65     
66     if (buf == NULL)
67     {
68        /* Skipping data */
69         while (count-- && fgetc(file) != EOF);
70         return count == 0;
71     }
72     
73     status = (fread(buf, 1, count, file) == count);
74     
75     if (feof(file))
76         stream->bytes_left = 0;
77     
78     return status;
79 }
80
81 int main()
82 {
83     /* Maximum size is specified to prevent infinite length messages from
84      * hanging this in the fuzz test.
85      */
86     pb_istream_t stream = {&callback, stdin, 10000};
87     if (!print_person(&stream))
88     {
89         printf("Parsing failed.\n");
90         return 1;
91     } else {
92         return 0;
93     }
94 }