decode_oneof.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* Decode a message using oneof fields */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <pb_decode.h>
  6. #include "oneof.pb.h"
  7. #include "test_helpers.h"
  8. #include "unittests.h"
  9. /* Test the 'AnonymousOneOfMessage' */
  10. int test_oneof_1(pb_istream_t *stream, int option)
  11. {
  12. AnonymousOneOfMessage msg;
  13. int status = 0;
  14. /* To better catch initialization errors */
  15. memset(&msg, 0xAA, sizeof(msg));
  16. if (!pb_decode(stream, AnonymousOneOfMessage_fields, &msg))
  17. {
  18. printf("Decoding failed: %s\n", PB_GET_ERROR(stream));
  19. return 1;
  20. }
  21. /* Check that the basic fields work normally */
  22. TEST(msg.prefix == 123);
  23. TEST(msg.suffix == 321);
  24. /* Check that we got the right oneof according to command line */
  25. if (option == 1)
  26. {
  27. TEST(msg.which_values == AnonymousOneOfMessage_first_tag);
  28. TEST(msg.first == 999);
  29. }
  30. else if (option == 2)
  31. {
  32. TEST(msg.which_values == AnonymousOneOfMessage_second_tag);
  33. TEST(strcmp(msg.second, "abcd") == 0);
  34. }
  35. else if (option == 3)
  36. {
  37. TEST(msg.which_values == AnonymousOneOfMessage_third_tag);
  38. TEST(msg.third.array[0] == 1);
  39. TEST(msg.third.array[1] == 2);
  40. TEST(msg.third.array[2] == 3);
  41. TEST(msg.third.array[3] == 4);
  42. TEST(msg.third.array[4] == 5);
  43. }
  44. return status;
  45. }
  46. int main(int argc, char **argv)
  47. {
  48. uint8_t buffer[AnonymousOneOfMessage_size];
  49. size_t count;
  50. int option;
  51. if (argc != 2)
  52. {
  53. fprintf(stderr, "Usage: decode_oneof [number]\n");
  54. return 1;
  55. }
  56. option = atoi(argv[1]);
  57. SET_BINARY_MODE(stdin);
  58. count = fread(buffer, 1, sizeof(buffer), stdin);
  59. if (!feof(stdin))
  60. {
  61. printf("Message does not fit in buffer\n");
  62. return 1;
  63. }
  64. {
  65. int status = 0;
  66. pb_istream_t stream;
  67. stream = pb_istream_from_buffer(buffer, count);
  68. status = test_oneof_1(&stream, option);
  69. if (status != 0)
  70. return status;
  71. }
  72. return 0;
  73. }