源码来自于 protobuf 3.5
//TestStruct.proto
message Pos{
uint32 x = 1;
uint32 y = 2;
}
Pos p;
p.set_x(1);
std::string s1 = p.SerializeAsString();
可以看到 s1.size() = 2
查看内存得到 十六进制为 0x 08 01 二进制位 00001000 0000 0001
查看生成的 TestStruct.pb.cc 文件
来看看 Pos::SerializeWithCachedSizes 的实现
// optional uint32 x = 1 [default = 0];
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->x(), output);
从头文件已经得知 0x00000001u 表示 x字段的编号
::google::protobuf::internal::WireFormatLite::WriteUInt32 函数的意思是把编号为1 的字段 写到stream
在 write_format_lite.cc 里找到
void WireFormatLite::WriteInt32(int field_number, int32 value,
io::CodedOutputStream* output)

本文深入分析protobuf 3.5的源码,揭示如何通过内存优化技术减少内存使用。通过示例展示 Pos消息序列化过程,解释字段编号、WIRETYPE_VARINT及tag的生成方式,说明protobuf如何利用最高位标识后续字节,从而理解为何128值需要两个字节,而65535值需要三个字节。
最低0.47元/天 解锁文章
2970

被折叠的 条评论
为什么被折叠?



