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#include "test_helpers.h" 13 14/* This function is called once from main(), it handles 15 the decoding and printing. */ 16bool print_person(pb_istream_t *stream) 17{ 18 int i; 19 Person person; 20 21 if (!pb_decode(stream, Person_fields, &person)) 22 return false; 23 24 /* Now the decoding is done, rest is just to print stuff out. */ 25 26 printf("name: \"%s\"\n", person.name); 27 printf("id: %ld\n", (long)person.id); 28 29 if (person.has_email) 30 printf("email: \"%s\"\n", person.email); 31 32 for (i = 0; i < person.phone_count; i++) 33 { 34 Person_PhoneNumber *phone = &person.phone[i]; 35 printf("phone {\n"); 36 printf(" number: \"%s\"\n", phone->number); 37 38 if (phone->has_type) 39 { 40 switch (phone->type) 41 { 42 case Person_PhoneType_WORK: 43 printf(" type: WORK\n"); 44 break; 45 46 case Person_PhoneType_HOME: 47 printf(" type: HOME\n"); 48 break; 49 50 case Person_PhoneType_MOBILE: 51 printf(" type: MOBILE\n"); 52 break; 53 } 54 } 55 printf("}\n"); 56 } 57 58 return true; 59} 60 61int main() 62{ 63 uint8_t buffer[Person_size]; 64 pb_istream_t stream; 65 size_t count; 66 67 /* Read the data into buffer */ 68 SET_BINARY_MODE(stdin); 69 count = fread(buffer, 1, sizeof(buffer), stdin); 70 71 if (!feof(stdin)) 72 { 73 printf("Message does not fit in buffer\n"); 74 return 1; 75 } 76 77 /* Construct a pb_istream_t for reading from the buffer */ 78 stream = pb_istream_from_buffer(buffer, count); 79 80 /* Decode and print out the stuff */ 81 if (!print_person(&stream)) 82 { 83 printf("Parsing failed: %s\n", PB_GET_ERROR(&stream)); 84 return 1; 85 } else { 86 return 0; 87 } 88} 89