Created
February 7, 2021 07:18
-
-
Save askdaddy/5ba0b9469acf24f169a4af8261a1307a to your computer and use it in GitHub Desktop.
asio+protobuf
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
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