Files

88 lines
2.2 KiB
C
Raw Permalink Normal View History

2011-09-12 18:53:33 +00:00
/* A very simple decoding test case, using person.proto.
* Produces output compatible with protoc --decode.
* Reads the encoded data from stdin and prints the values
* to stdout as text.
*
* Run e.g. ./test_encode1 | ./test_decode1
2011-09-12 18:53:33 +00:00
*/
2011-07-25 20:42:48 +00:00
#include <stdio.h>
2011-07-31 12:55:09 +00:00
#include <pb_decode.h>
2011-08-24 12:13:24 +00:00
#include "person.pb.h"
2013-09-10 17:44:32 +03:00
#include "test_helpers.h"
2011-07-25 20:42:48 +00:00
/* This function is called once from main(), it handles
the decoding and printing. */
2011-07-25 20:42:48 +00:00
bool print_person(pb_istream_t *stream)
{
2011-07-27 19:22:11 +00:00
int i;
Person person = Person_init_zero;
2011-07-25 20:42:48 +00:00
2011-07-27 19:22:11 +00:00
if (!pb_decode(stream, Person_fields, &person))
2011-07-25 20:42:48 +00:00
return false;
/* Now the decoding is done, rest is just to print stuff out. */
2011-08-17 19:03:06 +00:00
printf("name: \"%s\"\n", person.name);
printf("id: %ld\n", (long)person.id);
2011-08-17 19:03:06 +00:00
if (person.has_email)
printf("email: \"%s\"\n", person.email);
2011-07-27 19:22:11 +00:00
2011-07-31 12:55:09 +00:00
for (i = 0; i < person.phone_count; i++)
2011-07-27 19:22:11 +00:00
{
Person_PhoneNumber *phone = &person.phone[i];
2011-08-17 19:03:06 +00:00
printf("phone {\n");
printf(" number: \"%s\"\n", phone->number);
if (phone->has_type)
2011-08-17 19:03:06 +00:00
{
switch (phone->type)
{
case Person_PhoneType_WORK:
printf(" type: WORK\n");
break;
case Person_PhoneType_HOME:
printf(" type: HOME\n");
break;
case Person_PhoneType_MOBILE:
printf(" type: MOBILE\n");
break;
}
2011-08-17 19:03:06 +00:00
}
printf("}\n");
2011-07-27 19:22:11 +00:00
}
2011-07-25 20:42:48 +00:00
return true;
}
int main()
{
uint8_t buffer[Person_size];
2013-09-10 17:44:32 +03:00
pb_istream_t stream;
size_t count;
/* Read the data into buffer */
SET_BINARY_MODE(stdin);
count = fread(buffer, 1, sizeof(buffer), stdin);
if (!feof(stdin))
{
printf("Message does not fit in buffer\n");
return 1;
}
/* Construct a pb_istream_t for reading from the buffer */
2013-09-10 17:44:32 +03:00
stream = pb_istream_from_buffer(buffer, count);
/* Decode and print out the stuff */
2011-07-25 20:42:48 +00:00
if (!print_person(&stream))
{
printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
return 1;
} else {
return 0;
}
2011-07-25 20:42:48 +00:00
}