Protocol buffers - unique numbered tag - clarification?

前端 未结 2 407
囚心锁ツ
囚心锁ツ 2021-01-30 17:04

I\'m using protocol buffers and everything is working fine. except that the fact that I don\'t understand - why do I need the numbered tags in the proto file :

相关标签:
2条回答
  • 2021-01-30 17:35

    These field numbers are used by protobuf while encoding and decoding. See here for more details.

    So each and every field has wire type so int32 has wire type as 0 and your field number say is 2 so it will be encoded as 0001 0000 i.e. 10 in hex.

    And later on when its decoded, its left shifted by 1 which makes it as 001 0000 and last three lsb decides wire type i.e. it then makes out its of type int field and rest decides which field in proto it is i.e. 00010 is 2. So field 2 of wire type 0 (int)

    0 讨论(0)
  • 2021-01-30 17:41

    The numbered tags are used to match fields when serializing and deserializing the data.

    Obviously, if you change the numbering scheme, and apply this change to both serializer and deserializer, there is no issue.

    Consider though, if you saved data with the first numbering scheme, and loaded it with the second one, it would try to load query into result_per_page, and deserialization would likely fail.

    Now, why is this useful? Let's say you need to add another field to your data, long after the schema is already in use:

    message SearchRequest {
      required string query = 1;
      optional int32 page_number = 2;
      optional int32 result_per_page = 3;
      optional int32 new_data = 4;
    }
    

    Because you explicitly give it a number, your deserializer is still able to load data serialized with the old numbering scheme, ignoring deserialization of non-existent data.

    0 讨论(0)
提交回复
热议问题