gpt4 book ai didi

c++ - 解析文本格式的 protobuf 消息时如何忽略错误的字段

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:30 25 4
gpt4 key购买 nike

我在 C++ 中用错误的字段模拟了一个文本格式的文件解析。

我的简单测试 .proto 文件:

$ cat settings.proto
package settings;
message Settings {
optional int32 param1 = 1;
optional string param2 = 2;
optional bytes param3 = 3;
}

我的文本格式文件:

$ cat settings.txt
param1: 123
param: "some string"
param3: "another string"

我正在使用 google::protobuf::TextFormat::Parser 解析文件:

#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <fstream>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>

#include <settings.pb.h>

using namespace std;

int main( int argc, char* argv[] )
{
GOOGLE_PROTOBUF_VERIFY_VERSION;

settings::Settings settings;

int fd = open( argv[1], O_RDONLY );
if( fd < 0 )
{
cerr << " Error opening the file " << endl;
return false;
}

google::protobuf::io::finputStream finput( fd );
finput.SetCloseOnDelete( true );

google::protobuf::TextFormat::Parser parser;
parser.AllowPartialMessage( true );

if ( !parser.Parce( &finput, &settings ) )
{
cerr << "Failed to parse file!" << endl;
}

cout << settings.DebugString() << endl;

google::protobuf::ShutdownProtobufLibrary();

std::cout << "Exit" << std::endl;
return true;
}

我将解析器的 AllowPartialMessage 设置为 true。所有字段都是可选的。但目前 Parse 在第一个错误字段后停止解析。解析后“设置”仅包含一个第一个字段。

有没有办法通知失败并继续解析另一个正确的字段?

最佳答案

文本格式解析器不允许未知字段。文本格式旨在与人类交流,而人类会出现拼写错误。重要的是要检测这些拼写错误,而不是默默地忽略它们。

通常,忽略未知字段的原因是为了向前兼容:这样您的程序就可以(部分)理解针对具有新字段的协议(protocol)的 future 版本编写的消息。我经常看到两个特殊的用例:

  • 以文本格式进行机器对机器通信的系统。我建议不要这样做。相反,请使用二进制格式,或者如果您真的希望机器对机器的通信是文本的,请使用 JSON。

  • 人工编写文本格式配置文件,然后将其分发到生产中可能较旧的服务器的系统。在这种情况下,我建议使用在人类桌面上运行的工具将文本格式的 protobuf“预编译”为二进制,然后只将二进制消息发送到生产服务器。本地工具可以很容易地保持最新,并且能够在人类用户拼错字段名称时告知他们。

关于c++ - 解析文本格式的 protobuf 消息时如何忽略错误的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34890812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com