[关闭]
@iStarLee 2020-06-14T16:43:52.000000Z 字数 2013 阅读 404

protobuf

pony


Ref Website

1 主要特点

2 格式

  1. syntax = "proto2";
  2. package tutorial;
  3. import "other.proto"; # 引入其他proto
  4. message Person {
  5. required string name = 1; # 必须要有
  6. required int32 id = 2;
  7. optional string email = 3; # 可选,真实数据中不一定要有
  8. enum PhoneType {
  9. MOBILE = 0;
  10. HOME = 1;
  11. WORK = 2;
  12. }
  13. message PhoneNumber {
  14. required string number = 1; # 动态数组
  15. optional PhoneType type = 2 [default = HOME];
  16. }
  17. repeated PhoneNumber phones = 4;
  18. }
  19. message AddressBook {
  20. repeated Person people = 1;
  21. }

字段是以[ "repeated" ] type fieldName "=" fieldNumber [ "[" fieldOptions "]" ] ";"格式定义的

image_1eappoj301ufi1vd61r45h7e1sql9.png-63.9kB

每个元素上的“= 1”、“= 2”标记标识字段在二进制编码中使用的唯一“标记”。标签号1-15比更高的数字需要少一个字节的编码,因此作为优化,您可以决定对常用或重复的元素使用这些标签,对不常用的可选元素使用标签号16或更高。重复字段中的每个元素都需要对标签号进行重新编码,因此重复字段尤其适合于这种优化。

3 API

  1. // name
  2. inline bool has_name() const;
  3. inline void clear_name();
  4. inline const ::std::string& name() const;
  5. inline void set_name(const ::std::string& value);
  6. inline void set_name(const char* value);
  7. inline ::std::string* mutable_name();
  8. // id
  9. inline bool has_id() const;
  10. inline void clear_id();
  11. inline int32_t id() const;
  12. inline void set_id(int32_t value);
  13. // email
  14. inline bool has_email() const;
  15. inline void clear_email();
  16. inline const ::std::string& email() const;
  17. inline void set_email(const ::std::string& value);
  18. inline void set_email(const char* value);
  19. inline ::std::string* mutable_email();
  20. // phones
  21. inline int phones_size() const;
  22. inline void clear_phones();
  23. inline const ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >& phones() const;
  24. inline ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >* mutable_phones();
  25. inline const ::tutorial::Person_PhoneNumber& phones(int index) const;
  26. inline ::tutorial::Person_PhoneNumber* mutable_phones(int index);
  27. inline ::tutorial::Person_PhoneNumber* add_phones();

对于single 类型的数据,has_xx()
对于repeated 类型数据,xx_size()
大家公有clear_xx(),xx() get方法,set_xx set方法。
对于string或者repeated方法,mutable_xx
对于repeated,还有xx(index),xxs(),add_xx()

4 Standard Message Methods

image_1eapqcp7gr761l971994jka1a5qm.png-39.2kB

5 Parsing and Serialization

image_1eapqei641d471l6o1v77lhti1n13.png-49.3kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注