|
@@ -0,0 +1,70 @@
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+#include "ProtobufMessageRW.h"
|
|
|
+#include <google/protobuf/io/coded_stream.h>
|
|
|
+#include <google/protobuf/io/zero_copy_stream_impl.h>
|
|
|
+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;
|
|
|
+ }
|
|
|
+
|
|
|
+ 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;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ delete coded_output;
|
|
|
+ delete raw_output;
|
|
|
+ fflush(stdout);
|
|
|
+ return 0;
|
|
|
+}
|
|
|
+
|
|
|
+void ProtobufMessageRW::set_fd(int given_fd) {
|
|
|
+ fd = given_fd;
|
|
|
+}
|