protobuf的GZIP压缩

本文介绍了如何使用protobuf进行GZIP压缩。在序列化protobuf消息到iostream或string时,可以利用GzipOutputStream和GzipInputStream进行压缩和解压缩操作。在序列化过程中,需设置 compression_level 和 format,然后使用Close或Flush确保数据被写入。反序列化时,通过ArrayInputStream读取已压缩的string。注意序列化用StringOutputStream,反序列化用ArrayInputStream。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

protobuf的GZIP压缩

protobuf自带压缩功能,可选的压缩算法有 GZIP 和 ZLIB

序列化至iostream

序列化示例:

std::ofstream output("scene.art", std::ofstream::out | std::ofstream::trunc | std::ofstream::binary);
OstreamOutputStream outputFileStream(&output);
GzipOutputStream::Options options;
options.format = GzipOutputStream::GZIP;
options.compression_level = _COMPRESSION_LEVEL;
GzipOutputStream gzipOutputStream(&outputFileStream, &options);
scene->SerializeToZeroCopyStream(&gzipOutputStream);

反序列化示例:

std::ifstream input("scene.art", std::ifstream::in | std::ifstream::binary);
IstreamInputStream inputFileStream(&input);
GzipInputStream GzipInputStream(&inputFileStream);
scene1->ParseFromZeroCopyStream(&GzipInputStream);

序列化至string

序列化示例:

#include <google/protobuf/io/gzip_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
std::string output;
// 压缩序列化
google::protobuf::io::GzipOutputStream::Options options;
options.format = google::protobuf::io::GzipOutputStream::GZIP;
options.compression_level = 9;
google::protobuf::io::StringOutputStream outputStream(&output);
google::protobuf::io::GzipOutputStream gzipStream(&outputStream, options);
person.SerializeToZeroCopyStream(&gzipStream)
gzipStream.Close(); //数据刷到储存中

反序列化示例:

google::protobuf::io::ArrayInputStream inputStream(output.data(), output.size());
google::protobuf::io::GzipInputStream gzipStream(&inputStream);
person.ParseFromZeroCopyStream(&gzipStream)

需要注意:
1)序列化需要用 StringOutputStream ,对应的反序列化需要用 ArrayInputStream 。没有StringinputStream类。源码中的说明如下:
在这里插入图片描述
2)压缩序列化的时候,必须进行 Close 或者 Flush 操作

参考链接:
protobuf 启用 GZIP 压缩功能

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值