Example
[apps/agl-service-can-low-level.git] / tests / test_decode1.c
1 #include <stdio.h>
2 #include <pb_decode.h>
3 #include "person.h"
4
5 bool print_person(pb_istream_t *stream)
6 {
7     int i;
8     Person person;
9     
10     if (!pb_decode(stream, Person_fields, &person))
11         return false;
12     
13     printf("name: \"%s\"\n", person.name);
14     printf("id: %d\n", person.id);
15     
16     if (person.has_email)
17         printf("email: \"%s\"\n", person.email);
18     
19     for (i = 0; i < person.phone_count; i++)
20     {
21         Person_PhoneNumber *phone = &person.phone[i];
22         printf("phone {\n");
23         printf("  number: \"%s\"\n", phone->number);
24         
25         switch (phone->type)
26         {
27             case Person_PhoneType_WORK:
28                 printf("  type: WORK\n");
29                 break;
30             
31             case Person_PhoneType_HOME:
32                 printf("  type: HOME\n");
33                 break;
34             
35             case Person_PhoneType_MOBILE:
36                 printf("  type: MOBILE\n");
37                 break;
38         }
39         printf("}\n");
40     }
41     
42     return true;
43 }
44
45 bool callback(pb_istream_t *stream, uint8_t *buf, size_t count)
46 {
47     FILE *file = (FILE*)stream->state;
48     bool status;
49     
50     if (buf == NULL)
51     {
52         while (count-- && fgetc(file) != EOF);
53         return count == 0;
54     }
55     
56     status = (fread(buf, 1, count, file) == count);
57     
58     if (feof(file))
59         stream->bytes_left = 0;
60     
61     return status;
62 }
63
64 int main()
65 {
66     pb_istream_t stream = {&callback, stdin, SIZE_MAX};
67     if (!print_person(&stream))
68         printf("Parsing failed.\n");
69     
70     return 0;
71 }