encode_oneof.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Encode a message using oneof fields */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <pb_encode.h>
  5. #include "oneof.pb.h"
  6. #include "test_helpers.h"
  7. int main(int argc, char **argv)
  8. {
  9. uint8_t buffer[OneOfMessage_size];
  10. OneOfMessage msg = OneOfMessage_init_zero;
  11. pb_ostream_t stream;
  12. int option;
  13. if (argc != 2)
  14. {
  15. fprintf(stderr, "Usage: encode_oneof [number]\n");
  16. return 1;
  17. }
  18. option = atoi(argv[1]);
  19. /* Prefix and suffix are used to test that the union does not disturb
  20. * other fields in the same message. */
  21. msg.prefix = 123;
  22. /* We encode one of the 'values' fields based on command line argument */
  23. if (option == 1)
  24. {
  25. msg.which_values = OneOfMessage_first_tag;
  26. msg.values.first = 999;
  27. }
  28. else if (option == 2)
  29. {
  30. msg.which_values = OneOfMessage_second_tag;
  31. strcpy(msg.values.second, "abcd");
  32. }
  33. else if (option == 3)
  34. {
  35. msg.which_values = OneOfMessage_third_tag;
  36. msg.values.third.array_count = 5;
  37. msg.values.third.array[0] = 1;
  38. msg.values.third.array[1] = 2;
  39. msg.values.third.array[2] = 3;
  40. msg.values.third.array[3] = 4;
  41. msg.values.third.array[4] = 5;
  42. }
  43. msg.suffix = 321;
  44. stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  45. if (pb_encode(&stream, OneOfMessage_fields, &msg))
  46. {
  47. SET_BINARY_MODE(stdout);
  48. fwrite(buffer, 1, stream.bytes_written, stdout);
  49. return 0;
  50. }
  51. else
  52. {
  53. fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
  54. return 1;
  55. }
  56. }