// // Created by miti on 2019-12-24. // #include "ProtobufMessageRW.h" #include #include using namespace google::protobuf::io; int ProtobufMessageRW::read_msg(google::protobuf::MessageLite& message) { if(fd < 0) { printf("Need to call set_fd on this object first, to set the fd to a non-negative number.\n"); fflush(stdout); return 0x2; } ZeroCopyInputStream* raw_input; CodedInputStream* coded_input; uint32_t size; CodedInputStream::Limit limit; raw_input = new FileInputStream(fd); coded_input = new CodedInputStream(raw_input); if(!coded_input->ReadVarint32(&size)) { printf("Error in reading size of msg"); fflush(stdout); return -1; } //printf("size of msg was read to be %" PRIu32 " \n", size); fflush(stdout); limit = coded_input->PushLimit(size); if(!message.ParseFromCodedStream(coded_input)) { printf("Error in parsing msg"); fflush(stdout); return -1; } coded_input->PopLimit(limit); return 0; } int ProtobufMessageRW::write_msg(google::protobuf::MessageLite& message) { if(fd < 0) { printf("Need to call set_fd on this object first, to set the fd to a non-negative number.\n"); fflush(stdout); return 0x2; } ZeroCopyOutputStream* raw_output = new FileOutputStream(fd); CodedOutputStream* coded_output = new CodedOutputStream(raw_output); coded_output->WriteVarint32(message.ByteSize()); if(!message.SerializeToCodedStream(coded_output)) { printf("SerializeToCodedStream failed"); fflush(stdout); return -1; } // As per this - https://stackoverflow.com/questions/22881876/protocol-buffers-how-to-serialize-and-deserialize-multiple-messages-into-a-file?noredirect=1&lq=1 // 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) delete coded_output; delete raw_output; fflush(stdout); return 0; } void ProtobufMessageRW::set_fd(int given_fd) { fd = given_fd; }