wire_format.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc.
  3. # http://code.google.com/p/protobuf/
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Constants and static functions to support protocol buffer wire format."""
  17. __author__ = 'robinson@google.com (Will Robinson)'
  18. import struct
  19. from google.protobuf import message
  20. TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag.
  21. _TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7
  22. # These numbers identify the wire type of a protocol buffer value.
  23. # We use the least-significant TAG_TYPE_BITS bits of the varint-encoded
  24. # tag-and-type to store one of these WIRETYPE_* constants.
  25. # These values must match WireType enum in //net/proto2/public/wire_format.h.
  26. WIRETYPE_VARINT = 0
  27. WIRETYPE_FIXED64 = 1
  28. WIRETYPE_LENGTH_DELIMITED = 2
  29. WIRETYPE_START_GROUP = 3
  30. WIRETYPE_END_GROUP = 4
  31. WIRETYPE_FIXED32 = 5
  32. _WIRETYPE_MAX = 5
  33. # Bounds for various integer types.
  34. INT32_MAX = int((1 << 31) - 1)
  35. INT32_MIN = int(-(1 << 31))
  36. UINT32_MAX = (1 << 32) - 1
  37. INT64_MAX = (1 << 63) - 1
  38. INT64_MIN = -(1 << 63)
  39. UINT64_MAX = (1 << 64) - 1
  40. # "struct" format strings that will encode/decode the specified formats.
  41. FORMAT_UINT32_LITTLE_ENDIAN = '<I'
  42. FORMAT_UINT64_LITTLE_ENDIAN = '<Q'
  43. # We'll have to provide alternate implementations of AppendLittleEndian*() on
  44. # any architectures where these checks fail.
  45. if struct.calcsize(FORMAT_UINT32_LITTLE_ENDIAN) != 4:
  46. raise AssertionError('Format "I" is not a 32-bit number.')
  47. if struct.calcsize(FORMAT_UINT64_LITTLE_ENDIAN) != 8:
  48. raise AssertionError('Format "Q" is not a 64-bit number.')
  49. def PackTag(field_number, wire_type):
  50. """Returns an unsigned 32-bit integer that encodes the field number and
  51. wire type information in standard protocol message wire format.
  52. Args:
  53. field_number: Expected to be an integer in the range [1, 1 << 29)
  54. wire_type: One of the WIRETYPE_* constants.
  55. """
  56. if not 0 <= wire_type <= _WIRETYPE_MAX:
  57. raise message.EncodeError('Unknown wire type: %d' % wire_type)
  58. return (field_number << TAG_TYPE_BITS) | wire_type
  59. def UnpackTag(tag):
  60. """The inverse of PackTag(). Given an unsigned 32-bit number,
  61. returns a (field_number, wire_type) tuple.
  62. """
  63. return (tag >> TAG_TYPE_BITS), (tag & _TAG_TYPE_MASK)
  64. def ZigZagEncode(value):
  65. """ZigZag Transform: Encodes signed integers so that they can be
  66. effectively used with varint encoding. See wire_format.h for
  67. more details.
  68. """
  69. if value >= 0:
  70. return value << 1
  71. return (value << 1) ^ (~0)
  72. def ZigZagDecode(value):
  73. """Inverse of ZigZagEncode()."""
  74. if not value & 0x1:
  75. return value >> 1
  76. return (value >> 1) ^ (~0)
  77. # The *ByteSize() functions below return the number of bytes required to
  78. # serialize "field number + type" information and then serialize the value.
  79. def Int32ByteSize(field_number, int32):
  80. return Int64ByteSize(field_number, int32)
  81. def Int64ByteSize(field_number, int64):
  82. # Have to convert to uint before calling UInt64ByteSize().
  83. return UInt64ByteSize(field_number, 0xffffffffffffffff & int64)
  84. def UInt32ByteSize(field_number, uint32):
  85. return UInt64ByteSize(field_number, uint32)
  86. def UInt64ByteSize(field_number, uint64):
  87. return _TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64)
  88. def SInt32ByteSize(field_number, int32):
  89. return UInt32ByteSize(field_number, ZigZagEncode(int32))
  90. def SInt64ByteSize(field_number, int64):
  91. return UInt64ByteSize(field_number, ZigZagEncode(int64))
  92. def Fixed32ByteSize(field_number, fixed32):
  93. return _TagByteSize(field_number) + 4
  94. def Fixed64ByteSize(field_number, fixed64):
  95. return _TagByteSize(field_number) + 8
  96. def SFixed32ByteSize(field_number, sfixed32):
  97. return _TagByteSize(field_number) + 4
  98. def SFixed64ByteSize(field_number, sfixed64):
  99. return _TagByteSize(field_number) + 8
  100. def FloatByteSize(field_number, flt):
  101. return _TagByteSize(field_number) + 4
  102. def DoubleByteSize(field_number, double):
  103. return _TagByteSize(field_number) + 8
  104. def BoolByteSize(field_number, b):
  105. return _TagByteSize(field_number) + 1
  106. def EnumByteSize(field_number, enum):
  107. return UInt32ByteSize(field_number, enum)
  108. def StringByteSize(field_number, string):
  109. return (_TagByteSize(field_number)
  110. + _VarUInt64ByteSizeNoTag(len(string))
  111. + len(string))
  112. def BytesByteSize(field_number, b):
  113. return StringByteSize(field_number, b)
  114. def GroupByteSize(field_number, message):
  115. return (2 * _TagByteSize(field_number) # START and END group.
  116. + message.ByteSize())
  117. def MessageByteSize(field_number, message):
  118. return (_TagByteSize(field_number)
  119. + _VarUInt64ByteSizeNoTag(message.ByteSize())
  120. + message.ByteSize())
  121. def MessageSetItemByteSize(field_number, msg):
  122. # First compute the sizes of the tags.
  123. # There are 2 tags for the beginning and ending of the repeated group, that
  124. # is field number 1, one with field number 2 (type_id) and one with field
  125. # number 3 (message).
  126. total_size = (2 * _TagByteSize(1) + _TagByteSize(2) + _TagByteSize(3))
  127. # Add the number of bytes for type_id.
  128. total_size += _VarUInt64ByteSizeNoTag(field_number)
  129. message_size = msg.ByteSize()
  130. # The number of bytes for encoding the length of the message.
  131. total_size += _VarUInt64ByteSizeNoTag(message_size)
  132. # The size of the message.
  133. total_size += message_size
  134. return total_size
  135. # Private helper functions for the *ByteSize() functions above.
  136. def _TagByteSize(field_number):
  137. """Returns the bytes required to serialize a tag with this field number."""
  138. # Just pass in type 0, since the type won't affect the tag+type size.
  139. return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0))
  140. def _VarUInt64ByteSizeNoTag(uint64):
  141. """Returns the bytes required to serialize a single varint.
  142. uint64 must be unsigned.
  143. """
  144. if uint64 > UINT64_MAX:
  145. raise message.EncodeError('Value out of range: %d' % uint64)
  146. bytes = 1
  147. while uint64 > 0x7f:
  148. bytes += 1
  149. uint64 >>= 7
  150. return bytes