Java中协议缓冲区分隔的IO功能是否有C ++等效项?

Java中协议缓冲区分隔的IO功能是否有C ++等效项?,第1张

Java中协议缓冲区分隔的I / O功能是否有C ++等效项?

我在这里参加聚会有点晚,但是下面的实现包括其他答案中缺少的一些优化,并且在输入64MB后不会失败(尽管它仍然对每个单独的消息强制执行64MB的限制,只是对整个消息流没有限制))。

(我是C ++和Java protobuf库的作者,但我不再在Google上工作。很抱歉,此代码从未将其添加到官方lib中。如果有的话,它的样子。)

bool writeDelimitedTo(    const google::protobuf::MessageLite& message,    google::protobuf::io::ZeroCopyOutputStream* rawOutput) {  // We create a new pred 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 pred 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;}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5017566.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存