test.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "test.pb.h"
  2. #include <unittests.h>
  3. #include <pb_encode.h>
  4. #include <pb_decode.h>
  5. static bool write_array(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  6. {
  7. int i;
  8. for (i = 0; i < 5; i++)
  9. {
  10. if (!pb_encode_tag_for_field(stream, field))
  11. return false;
  12. if (!pb_encode_varint(stream, 1000 + i))
  13. return false;
  14. }
  15. return true;
  16. }
  17. static bool read_array(pb_istream_t *stream, const pb_field_t *field, void **arg)
  18. {
  19. uint32_t i;
  20. int *sum = *arg;
  21. if (!pb_decode_varint32(stream, &i))
  22. return false;
  23. *sum += i;
  24. return true;
  25. }
  26. int main()
  27. {
  28. int status = 0;
  29. pb_byte_t buf[128] = {0};
  30. pb_size_t msglen;
  31. {
  32. MainMessage msg = MainMessage_init_zero;
  33. pb_ostream_t stream = pb_ostream_from_buffer(buf, sizeof(buf));
  34. msg.submsg.foo.funcs.encode = &write_array;
  35. TEST(pb_encode(&stream, MainMessage_fields, &msg));
  36. msglen = stream.bytes_written;
  37. }
  38. {
  39. MainMessage msg = MainMessage_init_zero;
  40. pb_istream_t stream = pb_istream_from_buffer(buf, msglen);
  41. int sum = 0;
  42. msg.submsg.foo.funcs.decode = &read_array;
  43. msg.submsg.foo.arg = &sum;
  44. TEST(pb_decode(&stream, MainMessage_fields, &msg));
  45. TEST(sum == 1000 + 1001 + 1002 + 1003 + 1004);
  46. }
  47. return status;
  48. }