ProtobufMessageRW.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // Created by miti on 2019-12-24.
  3. //
  4. #include "ProtobufMessageRW.h"
  5. #include <google/protobuf/io/coded_stream.h>
  6. #include <google/protobuf/io/zero_copy_stream_impl.h>
  7. using namespace google::protobuf::io;
  8. int ProtobufMessageRW::read_msg(google::protobuf::MessageLite& message)
  9. {
  10. if(fd < 0)
  11. {
  12. printf("Need to call set_fd on this object first, to set the fd to a non-negative number.\n");
  13. fflush(stdout);
  14. return 0x2;
  15. }
  16. ZeroCopyInputStream* raw_input;
  17. CodedInputStream* coded_input;
  18. uint32_t size;
  19. CodedInputStream::Limit limit;
  20. raw_input = new FileInputStream(fd);
  21. coded_input = new CodedInputStream(raw_input);
  22. if(!coded_input->ReadVarint32(&size))
  23. {
  24. printf("Error in reading size of msg");
  25. fflush(stdout);
  26. return -1;
  27. }
  28. //printf("size of msg was read to be %" PRIu32 " \n", size);
  29. fflush(stdout);
  30. limit = coded_input->PushLimit(size);
  31. if(!message.ParseFromCodedStream(coded_input))
  32. {
  33. printf("Error in parsing msg");
  34. fflush(stdout);
  35. return -1;
  36. }
  37. coded_input->PopLimit(limit);
  38. return 0;
  39. }
  40. int ProtobufMessageRW::write_msg(google::protobuf::MessageLite& message)
  41. {
  42. if(fd < 0)
  43. {
  44. printf("Need to call set_fd on this object first, to set the fd to a non-negative number.\n");
  45. fflush(stdout);
  46. return 0x2;
  47. }
  48. ZeroCopyOutputStream* raw_output = new FileOutputStream(fd);
  49. CodedOutputStream* coded_output = new CodedOutputStream(raw_output);
  50. coded_output->WriteVarint32(message.ByteSize());
  51. if(!message.SerializeToCodedStream(coded_output))
  52. {
  53. printf("SerializeToCodedStream failed");
  54. fflush(stdout);
  55. return -1;
  56. }
  57. // As per this - https://stackoverflow.com/questions/22881876/protocol-buffers-how-to-serialize-and-deserialize-multiple-messages-into-a-file?noredirect=1&lq=1
  58. // TODO: There may be a better way to do this - 1) this happens with every accept now and 2) make it happen on the stack vs heap - destructor will be called on return from this function (main) and the items will then be written out. (We probably don't want that, actually)
  59. delete coded_output;
  60. delete raw_output;
  61. fflush(stdout);
  62. return 0;
  63. }
  64. void ProtobufMessageRW::set_fd(int given_fd) {
  65. fd = given_fd;
  66. }