encode_callbacks.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* Encoding testcase for callback fields */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <pb_encode.h>
  5. #include "callbacks.pb.h"
  6. #include "test_helpers.h"
  7. bool encode_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  8. {
  9. char *str = "Hello world!";
  10. if (!pb_encode_tag_for_field(stream, field))
  11. return false;
  12. return pb_encode_string(stream, (uint8_t*)str, strlen(str));
  13. }
  14. bool encode_int32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  15. {
  16. if (!pb_encode_tag_for_field(stream, field))
  17. return false;
  18. return pb_encode_varint(stream, 42);
  19. }
  20. bool encode_fixed32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  21. {
  22. uint32_t value = 42;
  23. if (!pb_encode_tag_for_field(stream, field))
  24. return false;
  25. return pb_encode_fixed32(stream, &value);
  26. }
  27. bool encode_fixed64(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  28. {
  29. uint64_t value = 42;
  30. if (!pb_encode_tag_for_field(stream, field))
  31. return false;
  32. return pb_encode_fixed64(stream, &value);
  33. }
  34. bool encode_repeatedstring(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  35. {
  36. char *str[4] = {"Hello world!", "", "Test", "Test2"};
  37. int i;
  38. for (i = 0; i < 4; i++)
  39. {
  40. if (!pb_encode_tag_for_field(stream, field))
  41. return false;
  42. if (!pb_encode_string(stream, (uint8_t*)str[i], strlen(str[i])))
  43. return false;
  44. }
  45. return true;
  46. }
  47. int main()
  48. {
  49. uint8_t buffer[1024];
  50. pb_ostream_t stream;
  51. TestMessage testmessage = {{{NULL}}};
  52. stream = pb_ostream_from_buffer(buffer, 1024);
  53. testmessage.stringvalue.funcs.encode = &encode_string;
  54. testmessage.int32value.funcs.encode = &encode_int32;
  55. testmessage.fixed32value.funcs.encode = &encode_fixed32;
  56. testmessage.fixed64value.funcs.encode = &encode_fixed64;
  57. testmessage.has_submsg = true;
  58. testmessage.submsg.stringvalue.funcs.encode = &encode_string;
  59. testmessage.submsg.int32value.funcs.encode = &encode_int32;
  60. testmessage.submsg.fixed32value.funcs.encode = &encode_fixed32;
  61. testmessage.submsg.fixed64value.funcs.encode = &encode_fixed64;
  62. testmessage.repeatedstring.funcs.encode = &encode_repeatedstring;
  63. if (!pb_encode(&stream, TestMessage_fields, &testmessage))
  64. return 1;
  65. SET_BINARY_MODE(stdout);
  66. if (fwrite(buffer, stream.bytes_written, 1, stdout) != 1)
  67. return 2;
  68. return 0;
  69. }