summaryrefslogtreecommitdiffstats
path: root/tests/test_decode1.c
blob: a2c7f4281a48bdd3fa4b6f79d0fe706d0ea0b323 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <pb_decode.h>
#include "person.h"

/* This test has only one source file anyway.. */
#include "person.c"

bool print_person(pb_istream_t *stream)
{
    int i;
    Person person;
    
    if (!pb_decode(stream, Person_fields, &person))
        return false;
    
    printf("Person: name '%s' id '%d' email '%s'\n", person.name, person.id, person.email);
    
    for (i = 0; i < person.phone_count; i++)
    {
        Person_PhoneNumber *phone = &person.phone[i];
        printf("PhoneNumber: number '%s' type '%d'\n", phone->number, phone->type);
    }
    
    return true;
}

bool callback(pb_istream_t *stream, uint8_t *buf, size_t count)
{
    FILE *file = (FILE*)stream->state;
    bool status;
    
    if (buf == NULL)
    {
        while (count-- && fgetc(file) != EOF);
        return count == 0;
    }
    
    status = (fread(buf, 1, count, file) == count);
    
    if (feof(file))
        stream->bytes_left = 0;
    
    return status;
}

int main()
{
    pb_istream_t stream = {&callback, stdin, SIZE_MAX};
    if (!print_person(&stream))
        printf("Parsing failed.\n");
    
    return 0;
}