๐Ÿ“Protobuf: calculating field size

Tag

Each field is prepended VarInt-encoded value: (field_number << 3) | wire_type

Max fieldnumber is 229โˆ’1=536,870,9112^{29}-1 = 536,870,911. 19,000 through 19,999 are reserved.

bytesbits availablemax field number
1415
2112047
318262143
42533554431
529536870911

Values

VarInt (wire type 0)

Protobuf extensively uses base128 encoding (VarInt).

bytesbits availablemax unsigned valuesigned minsigned max
17127-6463
21416383-81928191
3212097151-10485761048575
428268435455-134217728134217727
53534359738367-1717986918417179869183
6424398046511103-21990232555522199023255551
749562949953421311-281474976710656281474976710655
85672057594037927935-3602879701896396836028797018963967
9639223372036854775807-46116860184273879044611686018427387903
106418446744073709551615-92233720368547758089223372036854775807

VarInt encoding (int32, int64, uint32, uint64, sint32, sint64, bool, enum):

Length-delimited (wire type 2)

string, bytes, embedded messages, packed repeated fields

VarInt-encoded length + bytes

64-bit (wire type 1)

fixed64, sfixed64, double

8 bytes

32-bit (wire type 5)

fixed32, sfixed32, float

4 bytes

Packed repeated fields

Only VarInt, 32-bit, and 64-bit types can be packed.

Packed fields are encoded as:

  • wire type 2 (length delimited)

  • VarInt length

  • Next length bytes values go one after another without additional tags or separators

Backlinks