Created
June 21, 2015 16:53
-
-
Save simonlynen/e465ed32b05ebed2a22b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From Kenton Varda: http://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja | |
bool writeDelimitedTo( | |
const google::protobuf::MessageLite& message, | |
google::protobuf::io::ZeroCopyOutputStream* rawOutput) { | |
// We create a new coded stream for each message. Don't worry, this is fast. | |
google::protobuf::io::CodedOutputStream output(rawOutput); | |
// Write the size. | |
const int size = message.ByteSize(); | |
output.WriteVarint32(size); | |
uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size); | |
if (buffer != NULL) { | |
// Optimization: The message fits in one buffer, so use the faster | |
// direct-to-array serialization path. | |
message.SerializeWithCachedSizesToArray(buffer); | |
} else { | |
// Slightly-slower path when the message is multiple buffers. | |
message.SerializeWithCachedSizes(&output); | |
if (output.HadError()) return false; | |
} | |
return true; | |
} | |
bool readDelimitedFrom( | |
google::protobuf::io::ZeroCopyInputStream* rawInput, | |
google::protobuf::MessageLite* message) { | |
// We create a new coded stream for each message. Don't worry, this is fast, | |
// and it makes sure the 64MB total size limit is imposed per-message rather | |
// than on the whole stream. (See the CodedInputStream interface for more | |
// info on this limit.) | |
google::protobuf::io::CodedInputStream input(rawInput); | |
// Read the size. | |
uint32_t size; | |
if (!input.ReadVarint32(&size)) return false; | |
// Tell the stream not to read beyond that size. | |
google::protobuf::io::CodedInputStream::Limit limit = | |
input.PushLimit(size); | |
// Parse the message. | |
if (!message->MergeFromCodedStream(&input)) return false; | |
if (!input.ConsumedEntireMessage()) return false; | |
// Release the limit. | |
input.PopLimit(limit); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment