16 #include "absl/strings/str_cat.h"
17 #include "google/protobuf/descriptor.h"
18 #include "google/protobuf/io/zero_copy_stream_impl_lite.h"
19 #include "google/protobuf/message.h"
20 #include "google/protobuf/text_format.h"
27 using ::google::protobuf::TextFormat;
37 google::protobuf::Message*
proto) {
51 constexpr
double kMaxBinaryProtoParseShrinkFactor = 2;
52 if (
proto->ParseFromString(data)) {
58 proto->DiscardUnknownFields();
59 if (
proto->ByteSizeLong() <
60 data.size() / kMaxBinaryProtoParseShrinkFactor) {
61 VLOG(1) <<
"ReadFileToProto(): input may be a binary proto, but of a "
64 VLOG(1) <<
"ReadFileToProto(): input seems to be a binary proto";
68 if (google::protobuf::TextFormat::ParseFromString(data,
proto)) {
69 VLOG(1) <<
"ReadFileToProto(): input is a text proto";
72 LOG(WARNING) <<
"Could not parse protocol buffer";
77 const google::protobuf::Message&
proto,
79 bool append_extension_to_file_name) {
83 std::string file_type_suffix;
84 std::string output_string;
85 google::protobuf::io::StringOutputStream stream(&output_string);
86 switch (proto_write_format) {
88 if (!
proto.SerializeToZeroCopyStream(&stream)) {
89 LOG(WARNING) <<
"Serialize to stream failed.";
92 file_type_suffix =
".bin";
95 if (!google::protobuf::TextFormat::PrintToString(
proto, &output_string)) {
96 LOG(WARNING) <<
"Printing to string failed.";
101 std::string output_filename(filename);
102 if (append_extension_to_file_name) output_filename += file_type_suffix;
103 VLOG(1) <<
"Writing " << output_string.size() <<
" bytes to "
107 LOG(WARNING) <<
"Writing to file failed.";