ProtobufMessageRW.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // Created by miti on 2019-12-24.
  3. //
  4. #include "ProtobufMessageRW.h"
  5. int ProtobufMessageRW::read_msg(google::protobuf::MessageLite& message)
  6. {
  7. if(fd < 0)
  8. {
  9. printf("Need to call set_fd on this object first, to set the fd to a non-negative number.\n");
  10. fflush(stdout);
  11. return 0x2;
  12. }
  13. ZeroCopyInputStream* raw_input;
  14. CodedInputStream* coded_input;
  15. uint32_t size;
  16. CodedInputStream::Limit limit;
  17. raw_input = new FileInputStream(fd);
  18. coded_input = new CodedInputStream(raw_input);
  19. if(!coded_input->ReadVarint32(&size))
  20. {
  21. printf("Error in reading size of msg");
  22. fflush(stdout);
  23. return -1;
  24. }
  25. //printf("size of msg was read to be %" PRIu32 " \n", size);
  26. fflush(stdout);
  27. limit = coded_input->PushLimit(size);
  28. if(!message.ParseFromCodedStream(coded_input))
  29. {
  30. printf("Error in parsing msg");
  31. fflush(stdout);
  32. return -1;
  33. }
  34. coded_input->PopLimit(limit);
  35. return 0;
  36. }
  37. int ProtobufMessageRW::write_msg(google::protobuf::MessageLite& message)
  38. {
  39. if(fd < 0)
  40. {
  41. printf("Need to call set_fd on this object first, to set the fd to a non-negative number.\n");
  42. fflush(stdout);
  43. return 0x2;
  44. }
  45. ZeroCopyOutputStream* raw_output = new FileOutputStream(fd);
  46. CodedOutputStream* coded_output = new CodedOutputStream(raw_output);
  47. coded_output->WriteVarint32(message.ByteSize());
  48. if(!message.SerializeToCodedStream(coded_output))
  49. {
  50. printf("SerializeToCodedStream failed");
  51. fflush(stdout);
  52. return -1;
  53. }
  54. // As per this - https://stackoverflow.com/questions/22881876/protocol-buffers-how-to-serialize-and-deserialize-multiple-messages-into-a-file?noredirect=1&lq=1
  55. // 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)
  56. delete coded_output;
  57. delete raw_output;
  58. fflush(stdout);
  59. return 0;
  60. }
  61. uint32_t ProtobufMessageRW::set_fd(int given_fd) {
  62. fd = given_fd;
  63. }