」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 C++ 中為 Protocol Buffer 實現定界 I/O?

如何在 C++ 中為 Protocol Buffer 實現定界 I/O?

發佈於2024-11-26
瀏覽:192

 How to Implement Delimited I/O in C   for Protocol Buffers?

Protocol Buffers 中的定界I/O 函數:C 等效項

在從兩個協議緩衝區中的文件讀取取或寫入多個Protocol Buffers 訊息的情況下C 和Java,有必要在訊息中附加長度前綴。雖然 Java API 為此目的提供了專用的「定界」I/O 函數,但它們在 C 中的對應函數可能並不明顯。

最近的更新表明,此類 C 等效函數現在駐留在 google/protobuf/util 中/delimited_message_util.h 作為版本 3.3.0 的一部分。然而,在此更新之前,有一些替代實作可以有效地滿足此要求。

其中一個實作由 C 和 Java protobuf 函式庫的前作者提供,包括防止 64MB 輸入後潛在故障的最佳化。如下所示,這些實作對單一訊息強制實施 64MB 限制,確保串流媒體無縫繼續進行,而不會超出整體限制。

C 的最佳化定界 I/O 實作

bool writeDelimitedTo(
    const google::protobuf::MessageLite& message,
    google::protobuf::io::ZeroCopyOutputStream* rawOutput) {
  // Initialize a CodedOutputStream for each message.
  google::protobuf::io::CodedOutputStream output(rawOutput);

  // Determine the message size and write it as a Varint.
  int size = message.ByteSize();
  output.WriteVarint32(size);

  // Optimize for messages fitting into a single buffer.
  uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size);
  if (buffer != NULL) message.SerializeWithCachedSizesToArray(buffer);
  else message.SerializeWithCachedSizes(&output);

  return true;
}

bool readDelimitedFrom(
    google::protobuf::io::ZeroCopyInputStream* rawInput,
    google::protobuf::MessageLite* message) {
  // Initialize a CodedInputStream for each message.
  google::protobuf::io::CodedInputStream input(rawInput);

  // Read the message size.
  uint32_t size;
  if (!input.ReadVarint32(&size)) return false;

  // Restrict reading to the determined message size.
  google::protobuf::io::CodedInputStream::Limit limit =
      input.PushLimit(size);

  // Parse the message and verify it fits within the limit.
  if (!message->MergeFromCodedStream(&input)) return false;
  if (!input.ConsumedEntireMessage()) return false;

  // Lift the reading restriction.
  input.PopLimit(limit);

  return true;
}

這些最佳化的實作有效地處理不同大小的訊息,並為 C 中的分隔 I/O 提供可靠的解決方案。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3