Protobuf

# Part 1: Protobuf Intro

protobuf documentation详细介绍了关于protobuf的基本概念和初步使用法。
Protobuf是Google开源的一种可用于结构化数据串行化(序列化)的数据缓存格式,适用于数据存储以及RPC数据交换格式。Protobuf将一个文件结构化为多个message组合而成。
就我理解,好处有:

  1. 方便的序列化方式。提供了简单明了的接口来对自己定义好的结构化数据进行序列化和反序列化。
  2. 适合数据保密。若没有用户定义好的.proto格式,但看序列化到硬盘的文件很难知晓数据内容。
  3. 跨语言,定义一个.proto格式,再任何语言下均可以使用,使用提供的不同语言的wrapper即可。

# Part 2: Protobuf Installaiton in MacOS

官网下载protobuf,此时的最新版本是 3.6.1
解压下载的文件并进入该目录

./configure
make
make check
sudo make install

顺利安装后,使用which protocprotoc --version来查看proto版本。

# Part 3: Protobuf Definition

先看一个例子

syntax = "proto3"

package tutorial;

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;
 
  enum PhoneType{
      MOBILE = 0;
      HOME = 1;
      WORK = 2;
  }

 message PhoneNumber {
     required string number = 1;
     optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phones = 4;
}

message AddressBook {
  repeated Person people = 1;
}

开头是package的声明,用于防止不同工程下的重命名。

protobuf 自动生成了一系列成员函数以便对信息内数据进行访问,以上面的Person为例:

// name
inline bool has_name() const;
inline void clear_name();
inline const ::std::string& name() const;
inline void set_name(const ::std::string& value);
inline void set_name(const char * value);
inline ::std::string* mutable_name();

// id
inline bool has_id() const;
inline void clear_id();
inline int32_t id() const;
inline void set_id(int32_t value);

// email
inline bool has_email() const;
inline void clear_email();
inline const ::std::string& email() const;
inline void set_email(const ::std::string& value);
inline void set_email(const char* value);
inline ::std::string* mutable_email();

// phones
inline int phones_size() const;
inline void clear_phones();
inline const ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >& phones() const;
inline ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >* mutable_phones();
inline const ::tutorial::Person_PhoneNumber& phones(int index) const;
inline ::tutorial::Person_PhoneNumber* mutable_phones(int index);
inline ::tutorial::Person_PhoneNumber* add_phones();

有以下几类函数:
getters in lowercase : 和变量名字相同的函数名称。
setters in highercase: 在变量名字前加上set_。
clear: 用于将变量多置为空态。
除此之外,还有一系列mutable_函数,能够得到指向变量的指针。从而进行set或者get操作。mutable调用时,所有的变量会自动设置为空。
Repeated类型的信息域具有一些特殊的方法,如:
1)size
2)通过index 访问第几个元素
3)通过add
函数增加新的元素,此时也能返回该元素的指针

# Part 4: Protobuf in Bazel

WORKSPACE file:

http_archive(
    name = "com_google_protobuf",
    urls = [
        "https://mirror.bazel.build/github.com/google/protobuf/archive/v3.6.1.tar.gz",
        "https://github.com/google/protobuf/archive/v3.6.1.tar.gz",
      ],
    sha256 = "3d4e589d81b2006ca603c1ab712c9715a76227293032d05b26fca603f90b3f5b",
    strip_prefix = "protobuf-3.6.1",
)

BUILD file:

proto_library(
    name = "person_proto",
    srcs = ["Person.proto"],
)

# The cc_proto_library rule generates C++ code for a proto_library rule. It
# must have exactly one proto_library dependency. If you want to use multiple
# proto_library targets, create a separate cc_proto_library target for each
# of them.
#
# Remote repository "com_google_protobuf_cc" must be defined to use this rule.
cc_proto_library(
    name = "person_cc_proto",
    deps = [":person_proto"],
)

依赖关系需要按照:同目录,同工程,外部第三方的顺序

# Part 5: Protobuf with zlib

zlib是一个开源的压缩库,实现的deflate压缩算法,也是该库唯一实现的压缩算法。
Que's C++ Studio关于理解和使用zlib库很详细。
对.proto格式的数据字段进行压缩用到的是GZIP
一个简单的例子如下:

...
#include "scene.pb.h"

#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/gzip_stream.h>
...
unsigned int const _COMPRESSION_LEVEL = 9;
using namespace google::protobuf::io;

int main() {
    GOOGLE_PROTOBUF_VERIFY_VERSION;
    
    Recipe::Scene * scene = new Recipe::Scene();
    
    /*
      initialization date in scene
    */
    
    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);
    if (!scene->SerializeToZeroCopyStream(&gzipOutputStream))
    {
        std::cerr << "Failed to write scene." << std::endl;
        return -1;
    }
    Recipe::Scene * scene1 = new Recipe::Scene();
    {
        std::ifstream input("scene.art", std::ifstream::in | std::ifstream::binary);
        IstreamInputStream inputFileStream(&input);
        GzipInputStream GzipInputStream(&inputFileStream);
        if (!scene1->ParseFromZeroCopyStream(&GzipInputStream))
        {
              std::cerr << "Failed to read scene." << std::endl;
              return -1;
    }
    }
    std::cout << "scene1->imageData_size() " << scene1->imageData_size() << std::endl;
    google::protobuf::ShutdownProtobufLibrary();
    return 0;
}

即直接将.proto数据在序列化的同时进行压缩,对应的,在反序列时也是直接parse即可。

out: ofstream --> OstreamOutputStream --> GZipOutputStream
in: ifstream --> IstreamInputStream --> GZipInputStream
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容