encode_buffer.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /* A very simple encoding test case using person.proto.
  2. * Just puts constant data in the fields and encodes into
  3. * buffer, which is then written to stdout.
  4. */
  5. #include <stdio.h>
  6. #include <pb_encode.h>
  7. #include "person.pb.h"
  8. #include "test_helpers.h"
  9. int main()
  10. {
  11. uint8_t buffer[Person_size];
  12. pb_ostream_t stream;
  13. /* Initialize the structure with constants */
  14. Person person = {"Test Person 99", 99, true, "test@person.com",
  15. 3, {{"555-12345678", true, Person_PhoneType_MOBILE},
  16. {"99-2342", false, 0},
  17. {"1234-5678", true, Person_PhoneType_WORK},
  18. }};
  19. stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  20. /* Now encode it and check if we succeeded. */
  21. if (pb_encode(&stream, Person_fields, &person))
  22. {
  23. /* Write the result data to stdout */
  24. SET_BINARY_MODE(stdout);
  25. fwrite(buffer, 1, stream.bytes_written, stdout);
  26. return 0; /* Success */
  27. }
  28. else
  29. {
  30. fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
  31. return 1; /* Failure */
  32. }
  33. }