decode_buffer.c 2.2 KB

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