submsg_callback.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "submsg_callback.pb.h"
  2. #include <pb_encode.h>
  3. #include <pb_decode.h>
  4. #include "unittests.h"
  5. bool msg_callback(pb_istream_t *stream, const pb_field_t *field, void **arg)
  6. {
  7. /* This tests decoding the submessage already in the message level callback. */
  8. SubMessage *submsg = (SubMessage*)field->pData;
  9. if (!pb_decode(stream, SubMessage_fields, submsg))
  10. PB_RETURN_ERROR(stream, "submsg decode failed");
  11. if (submsg->foo != 1234)
  12. PB_RETURN_ERROR(stream, "submsg.foo wrong value");
  13. return true;
  14. }
  15. int main()
  16. {
  17. int status = 0;
  18. pb_byte_t buf[64];
  19. size_t msglen;
  20. {
  21. pb_ostream_t ostream = pb_ostream_from_buffer(buf, sizeof(buf));
  22. MyMessage msg = MyMessage_init_zero;
  23. msg.which_oneof = MyMessage_submsg_tag;
  24. msg.oneof.submsg.foo = 1234;
  25. if (!pb_encode(&ostream, MyMessage_fields, &msg))
  26. {
  27. fprintf(stderr, "pb_encode() failed: %s\n", PB_GET_ERROR(&ostream));
  28. return 1;
  29. }
  30. msglen = ostream.bytes_written;
  31. TEST(msglen > 0);
  32. }
  33. {
  34. pb_istream_t istream = pb_istream_from_buffer(buf, msglen);
  35. MyMessage msg = MyMessage_init_zero;
  36. msg.cb_oneof.funcs.decode = msg_callback;
  37. if (!pb_decode(&istream, MyMessage_fields, &msg))
  38. {
  39. fprintf(stderr, "pb_decode() failed: %s\n", PB_GET_ERROR(&istream));
  40. return 1;
  41. }
  42. }
  43. return status;
  44. }