protobufReadWrite.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // Created by miti on 21/07/19.
  3. //
  4. #include "protobufReadWrite.h"
  5. namespace protobufReadWrite {
  6. int read_protobuf_msg_from_fd(int accept_fd, google::protobuf::MessageLite &message)
  7. {
  8. ZeroCopyInputStream *raw_input;
  9. CodedInputStream *coded_input;
  10. uint32_t size;
  11. CodedInputStream::Limit limit;
  12. raw_input = new FileInputStream(accept_fd);
  13. coded_input = new CodedInputStream(raw_input);
  14. if (!coded_input->ReadVarint32(&size)) {
  15. printf("Error in reading size of msg");
  16. fflush(stdout);
  17. return -1;
  18. }
  19. //printf("size of msg was read to be %" PRIu32 " \n", size);
  20. fflush(stdout);
  21. limit = coded_input->PushLimit(size);
  22. if (!message.ParseFromCodedStream(coded_input)) {
  23. printf("Error in parsing msg");
  24. fflush(stdout);
  25. return -1;
  26. }
  27. coded_input->PopLimit(limit);
  28. delete raw_input;
  29. delete coded_input;
  30. return 0;
  31. }
  32. int write_protobuf_msg_to_fd(int accept_fd, google::protobuf::MessageLite &message)
  33. {
  34. ZeroCopyOutputStream *raw_output = new FileOutputStream(accept_fd);
  35. CodedOutputStream *coded_output = new CodedOutputStream(raw_output);
  36. coded_output->WriteVarint32(message.ByteSize());
  37. if (!message.SerializeToCodedStream(coded_output)) {
  38. printf("SerializeToCodedStream failed");
  39. fflush(stdout);
  40. return -1;
  41. }
  42. // As per this - https://stackoverflow.com/questions/22881876/protocol-buffers-how-to-serialize-and-deserialize-multiple-messages-into-a-file?noredirect=1&lq=1
  43. // 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)
  44. delete coded_output;
  45. delete raw_output;
  46. fflush(stdout);
  47. return 0;
  48. }
  49. };