decode_stream.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* Same as test_decode1 but reads from stdin directly.
  2. */
  3. #include <stdio.h>
  4. #include <pb_decode.h>
  5. #include "person.pb.h"
  6. #include "test_helpers.h"
  7. /* This function is called once from main(), it handles
  8. the decoding and printing.
  9. Ugly copy-paste from test_decode1.c. */
  10. bool print_person(pb_istream_t *stream)
  11. {
  12. int i;
  13. Person person = Person_init_zero;
  14. if (!pb_decode(stream, Person_fields, &person))
  15. return false;
  16. /* Now the decoding is done, rest is just to print stuff out. */
  17. printf("name: \"%s\"\n", person.name);
  18. printf("id: %ld\n", (long)person.id);
  19. if (person.has_email)
  20. printf("email: \"%s\"\n", person.email);
  21. for (i = 0; i < person.phone_count; i++)
  22. {
  23. Person_PhoneNumber *phone = &person.phone[i];
  24. printf("phone {\n");
  25. printf(" number: \"%s\"\n", phone->number);
  26. if (phone->has_type)
  27. {
  28. switch (phone->type)
  29. {
  30. case Person_PhoneType_WORK:
  31. printf(" type: WORK\n");
  32. break;
  33. case Person_PhoneType_HOME:
  34. printf(" type: HOME\n");
  35. break;
  36. case Person_PhoneType_MOBILE:
  37. printf(" type: MOBILE\n");
  38. break;
  39. }
  40. }
  41. printf("}\n");
  42. }
  43. return true;
  44. }
  45. /* This binds the pb_istream_t to stdin */
  46. bool callback(pb_istream_t *stream, uint8_t *buf, size_t count)
  47. {
  48. FILE *file = (FILE*)stream->state;
  49. size_t len = fread(buf, 1, count, file);
  50. if (len == count)
  51. {
  52. return true;
  53. }
  54. else
  55. {
  56. stream->bytes_left = 0;
  57. return false;
  58. }
  59. }
  60. int main()
  61. {
  62. pb_istream_t stream = {&callback, NULL, SIZE_MAX};
  63. stream.state = stdin;
  64. SET_BINARY_MODE(stdin);
  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. }