missing_fields.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* Checks that missing required fields are detected properly */
  2. #include <stdio.h>
  3. #include <pb_encode.h>
  4. #include <pb_decode.h>
  5. #include "missing_fields.pb.h"
  6. int main()
  7. {
  8. uint8_t buffer[512];
  9. size_t size;
  10. /* Create a message with one missing field */
  11. {
  12. MissingField msg = {0};
  13. pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  14. if (!pb_encode(&stream, MissingField_fields, &msg))
  15. {
  16. printf("Encode failed.\n");
  17. return 1;
  18. }
  19. size = stream.bytes_written;
  20. }
  21. /* Test that it decodes properly if we don't require that field */
  22. {
  23. MissingField msg = {0};
  24. pb_istream_t stream = pb_istream_from_buffer(buffer, size);
  25. if (!pb_decode(&stream, MissingField_fields, &msg))
  26. {
  27. printf("Decode failed: %s\n", PB_GET_ERROR(&stream));
  28. return 2;
  29. }
  30. }
  31. /* Test that it does *not* decode properly if we require the field */
  32. {
  33. AllFields msg = {0};
  34. pb_istream_t stream = pb_istream_from_buffer(buffer, size);
  35. if (pb_decode(&stream, AllFields_fields, &msg))
  36. {
  37. printf("Decode didn't detect missing field.\n");
  38. return 3;
  39. }
  40. }
  41. return 0; /* All ok */
  42. }