Can fields of .proto files start from scratch?

.proto everyone seems to start numbering their fields in one.

eg. https://developers.google.com/protocol-buffers/docs/proto#simple

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

If you use zero, it will make several messages one or more bytes less (i.e. those that have one or more field numbers of 16).

Since the key is just varint coding (fieldnum <<3 | fieldtype), I cannot immediately see why zero should not be used.

Is there a reason not to start numbering the fields to zero?

+5
source share
2 answers

One very immediate reason is that null field numbers are rejected by protoc :

 test.proto:2:28: Field numbers must be positive integers. 

As to why Buffer protocols were designed this way, I can only guess. One of the nice consequences of this is that a message with zeros will be detected as invalid. It can also be used to indicate "no field" inside as the return value in the implementation of the protocol buffers.

+5
source

Tag assignment

As you can see, each field in the message definition has a unique numbered tag. These tags are used to identify your fields in binary message format and should not change after using your message type. Please note that tags with values ​​in the range from 1 to 15 accept one byte for encoding, including the identification number and field type (this can be found in Buffer Buffer encoding). Tags in the range 16 to 2047 take two bytes. Therefore, you must reserve tags 1 through 15 for very common message elements. Be sure to leave room for common items that may be added in the future.

The smallest tag number that you can specify is 1, and the largest is 2 29 -1 or 536 870.911. You also cannot use numbers from 19000 to 19999 (FieldDescriptor :: kFirstReservedNumber via FieldDescriptor :: kLastReservedNumber), since they are reserved for implementing protocol buffers - the protocol buffer compiler will complain if you use one of these reserved numbers in your .proto. Similarly, you cannot use previously reserved tags.

https://developers.google.com/protocol-buffers/docs/proto

As in the document, 0 cannot be detected.

+1
source

Source: https://habr.com/ru/post/1206642/


All Articles