wire_format.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # http://code.google.com/p/protobuf/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Constants and static functions to support protocol buffer wire format."""
  31. __author__ = 'robinson@google.com (Will Robinson)'
  32. import struct
  33. from froofle.protobuf import message
  34. TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag.
  35. _TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7
  36. # These numbers identify the wire type of a protocol buffer value.
  37. # We use the least-significant TAG_TYPE_BITS bits of the varint-encoded
  38. # tag-and-type to store one of these WIRETYPE_* constants.
  39. # These values must match WireType enum in //net/proto2/public/wire_format.h.
  40. WIRETYPE_VARINT = 0
  41. WIRETYPE_FIXED64 = 1
  42. WIRETYPE_LENGTH_DELIMITED = 2
  43. WIRETYPE_START_GROUP = 3
  44. WIRETYPE_END_GROUP = 4
  45. WIRETYPE_FIXED32 = 5
  46. _WIRETYPE_MAX = 5
  47. # Bounds for various integer types.
  48. INT32_MAX = int((1 << 31) - 1)
  49. INT32_MIN = int(-(1 << 31))
  50. UINT32_MAX = (1 << 32) - 1
  51. INT64_MAX = (1 << 63) - 1
  52. INT64_MIN = -(1 << 63)
  53. UINT64_MAX = (1 << 64) - 1
  54. # "struct" format strings that will encode/decode the specified formats.
  55. FORMAT_UINT32_LITTLE_ENDIAN = '<I'
  56. FORMAT_UINT64_LITTLE_ENDIAN = '<Q'
  57. # We'll have to provide alternate implementations of AppendLittleEndian*() on
  58. # any architectures where these checks fail.
  59. if struct.calcsize(FORMAT_UINT32_LITTLE_ENDIAN) != 4:
  60. raise AssertionError('Format "I" is not a 32-bit number.')
  61. if struct.calcsize(FORMAT_UINT64_LITTLE_ENDIAN) != 8:
  62. raise AssertionError('Format "Q" is not a 64-bit number.')
  63. def PackTag(field_number, wire_type):
  64. """Returns an unsigned 32-bit integer that encodes the field number and
  65. wire type information in standard protocol message wire format.
  66. Args:
  67. field_number: Expected to be an integer in the range [1, 1 << 29)
  68. wire_type: One of the WIRETYPE_* constants.
  69. """
  70. if not 0 <= wire_type <= _WIRETYPE_MAX:
  71. raise message.EncodeError('Unknown wire type: %d' % wire_type)
  72. return (field_number << TAG_TYPE_BITS) | wire_type
  73. def UnpackTag(tag):
  74. """The inverse of PackTag(). Given an unsigned 32-bit number,
  75. returns a (field_number, wire_type) tuple.
  76. """
  77. return (tag >> TAG_TYPE_BITS), (tag & _TAG_TYPE_MASK)
  78. def ZigZagEncode(value):
  79. """ZigZag Transform: Encodes signed integers so that they can be
  80. effectively used with varint encoding. See wire_format.h for
  81. more details.
  82. """
  83. if value >= 0:
  84. return value << 1
  85. return (value << 1) ^ (~0)
  86. def ZigZagDecode(value):
  87. """Inverse of ZigZagEncode()."""
  88. if not value & 0x1:
  89. return value >> 1
  90. return (value >> 1) ^ (~0)
  91. # The *ByteSize() functions below return the number of bytes required to
  92. # serialize "field number + type" information and then serialize the value.
  93. def Int32ByteSize(field_number, int32):
  94. return Int64ByteSize(field_number, int32)
  95. def Int64ByteSize(field_number, int64):
  96. # Have to convert to uint before calling UInt64ByteSize().
  97. return UInt64ByteSize(field_number, 0xffffffffffffffff & int64)
  98. def UInt32ByteSize(field_number, uint32):
  99. return UInt64ByteSize(field_number, uint32)
  100. def UInt64ByteSize(field_number, uint64):
  101. return _TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64)
  102. def SInt32ByteSize(field_number, int32):
  103. return UInt32ByteSize(field_number, ZigZagEncode(int32))
  104. def SInt64ByteSize(field_number, int64):
  105. return UInt64ByteSize(field_number, ZigZagEncode(int64))
  106. def Fixed32ByteSize(field_number, fixed32):
  107. return _TagByteSize(field_number) + 4
  108. def Fixed64ByteSize(field_number, fixed64):
  109. return _TagByteSize(field_number) + 8
  110. def SFixed32ByteSize(field_number, sfixed32):
  111. return _TagByteSize(field_number) + 4
  112. def SFixed64ByteSize(field_number, sfixed64):
  113. return _TagByteSize(field_number) + 8
  114. def FloatByteSize(field_number, flt):
  115. return _TagByteSize(field_number) + 4
  116. def DoubleByteSize(field_number, double):
  117. return _TagByteSize(field_number) + 8
  118. def BoolByteSize(field_number, b):
  119. return _TagByteSize(field_number) + 1
  120. def EnumByteSize(field_number, enum):
  121. return UInt32ByteSize(field_number, enum)
  122. def StringByteSize(field_number, string):
  123. return BytesByteSize(field_number, string.encode('utf-8'))
  124. def BytesByteSize(field_number, b):
  125. return (_TagByteSize(field_number)
  126. + _VarUInt64ByteSizeNoTag(len(b))
  127. + len(b))
  128. def GroupByteSize(field_number, message):
  129. return (2 * _TagByteSize(field_number) # START and END group.
  130. + message.ByteSize())
  131. def MessageByteSize(field_number, message):
  132. return (_TagByteSize(field_number)
  133. + _VarUInt64ByteSizeNoTag(message.ByteSize())
  134. + message.ByteSize())
  135. def MessageSetItemByteSize(field_number, msg):
  136. # First compute the sizes of the tags.
  137. # There are 2 tags for the beginning and ending of the repeated group, that
  138. # is field number 1, one with field number 2 (type_id) and one with field
  139. # number 3 (message).
  140. total_size = (2 * _TagByteSize(1) + _TagByteSize(2) + _TagByteSize(3))
  141. # Add the number of bytes for type_id.
  142. total_size += _VarUInt64ByteSizeNoTag(field_number)
  143. message_size = msg.ByteSize()
  144. # The number of bytes for encoding the length of the message.
  145. total_size += _VarUInt64ByteSizeNoTag(message_size)
  146. # The size of the message.
  147. total_size += message_size
  148. return total_size
  149. # Private helper functions for the *ByteSize() functions above.
  150. def _TagByteSize(field_number):
  151. """Returns the bytes required to serialize a tag with this field number."""
  152. # Just pass in type 0, since the type won't affect the tag+type size.
  153. return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0))
  154. def _VarUInt64ByteSizeNoTag(uint64):
  155. """Returns the bytes required to serialize a single varint.
  156. uint64 must be unsigned.
  157. """
  158. if uint64 > UINT64_MAX:
  159. raise message.EncodeError('Value out of range: %d' % uint64)
  160. bytes = 1
  161. while uint64 > 0x7f:
  162. bytes += 1
  163. uint64 >>= 7
  164. return bytes