店播爬取Python脚本

wire_format.py 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  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 google.protobuf import descriptor
  34. from google.protobuf import message
  35. TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag.
  36. TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7
  37. # These numbers identify the wire type of a protocol buffer value.
  38. # We use the least-significant TAG_TYPE_BITS bits of the varint-encoded
  39. # tag-and-type to store one of these WIRETYPE_* constants.
  40. # These values must match WireType enum in google/protobuf/wire_format.h.
  41. WIRETYPE_VARINT = 0
  42. WIRETYPE_FIXED64 = 1
  43. WIRETYPE_LENGTH_DELIMITED = 2
  44. WIRETYPE_START_GROUP = 3
  45. WIRETYPE_END_GROUP = 4
  46. WIRETYPE_FIXED32 = 5
  47. _WIRETYPE_MAX = 5
  48. # Bounds for various integer types.
  49. INT32_MAX = int((1 << 31) - 1)
  50. INT32_MIN = int(-(1 << 31))
  51. UINT32_MAX = (1 << 32) - 1
  52. INT64_MAX = (1 << 63) - 1
  53. INT64_MIN = -(1 << 63)
  54. UINT64_MAX = (1 << 64) - 1
  55. # "struct" format strings that will encode/decode the specified formats.
  56. FORMAT_UINT32_LITTLE_ENDIAN = '<I'
  57. FORMAT_UINT64_LITTLE_ENDIAN = '<Q'
  58. FORMAT_FLOAT_LITTLE_ENDIAN = '<f'
  59. FORMAT_DOUBLE_LITTLE_ENDIAN = '<d'
  60. # We'll have to provide alternate implementations of AppendLittleEndian*() on
  61. # any architectures where these checks fail.
  62. if struct.calcsize(FORMAT_UINT32_LITTLE_ENDIAN) != 4:
  63. raise AssertionError('Format "I" is not a 32-bit number.')
  64. if struct.calcsize(FORMAT_UINT64_LITTLE_ENDIAN) != 8:
  65. raise AssertionError('Format "Q" is not a 64-bit number.')
  66. def PackTag(field_number, wire_type):
  67. """Returns an unsigned 32-bit integer that encodes the field number and
  68. wire type information in standard protocol message wire format.
  69. Args:
  70. field_number: Expected to be an integer in the range [1, 1 << 29)
  71. wire_type: One of the WIRETYPE_* constants.
  72. """
  73. if not 0 <= wire_type <= _WIRETYPE_MAX:
  74. raise message.EncodeError('Unknown wire type: %d' % wire_type)
  75. return (field_number << TAG_TYPE_BITS) | wire_type
  76. def UnpackTag(tag):
  77. """The inverse of PackTag(). Given an unsigned 32-bit number,
  78. returns a (field_number, wire_type) tuple.
  79. """
  80. return (tag >> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK)
  81. def ZigZagEncode(value):
  82. """ZigZag Transform: Encodes signed integers so that they can be
  83. effectively used with varint encoding. See wire_format.h for
  84. more details.
  85. """
  86. if value >= 0:
  87. return value << 1
  88. return (value << 1) ^ (~0)
  89. def ZigZagDecode(value):
  90. """Inverse of ZigZagEncode()."""
  91. if not value & 0x1:
  92. return value >> 1
  93. return (value >> 1) ^ (~0)
  94. # The *ByteSize() functions below return the number of bytes required to
  95. # serialize "field number + type" information and then serialize the value.
  96. def Int32ByteSize(field_number, int32):
  97. return Int64ByteSize(field_number, int32)
  98. def Int32ByteSizeNoTag(int32):
  99. return _VarUInt64ByteSizeNoTag(0xffffffffffffffff & int32)
  100. def Int64ByteSize(field_number, int64):
  101. # Have to convert to uint before calling UInt64ByteSize().
  102. return UInt64ByteSize(field_number, 0xffffffffffffffff & int64)
  103. def UInt32ByteSize(field_number, uint32):
  104. return UInt64ByteSize(field_number, uint32)
  105. def UInt64ByteSize(field_number, uint64):
  106. return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64)
  107. def SInt32ByteSize(field_number, int32):
  108. return UInt32ByteSize(field_number, ZigZagEncode(int32))
  109. def SInt64ByteSize(field_number, int64):
  110. return UInt64ByteSize(field_number, ZigZagEncode(int64))
  111. def Fixed32ByteSize(field_number, fixed32):
  112. return TagByteSize(field_number) + 4
  113. def Fixed64ByteSize(field_number, fixed64):
  114. return TagByteSize(field_number) + 8
  115. def SFixed32ByteSize(field_number, sfixed32):
  116. return TagByteSize(field_number) + 4
  117. def SFixed64ByteSize(field_number, sfixed64):
  118. return TagByteSize(field_number) + 8
  119. def FloatByteSize(field_number, flt):
  120. return TagByteSize(field_number) + 4
  121. def DoubleByteSize(field_number, double):
  122. return TagByteSize(field_number) + 8
  123. def BoolByteSize(field_number, b):
  124. return TagByteSize(field_number) + 1
  125. def EnumByteSize(field_number, enum):
  126. return UInt32ByteSize(field_number, enum)
  127. def StringByteSize(field_number, string):
  128. return BytesByteSize(field_number, string.encode('utf-8'))
  129. def BytesByteSize(field_number, b):
  130. return (TagByteSize(field_number)
  131. + _VarUInt64ByteSizeNoTag(len(b))
  132. + len(b))
  133. def GroupByteSize(field_number, message):
  134. return (2 * TagByteSize(field_number) # START and END group.
  135. + message.ByteSize())
  136. def MessageByteSize(field_number, message):
  137. return (TagByteSize(field_number)
  138. + _VarUInt64ByteSizeNoTag(message.ByteSize())
  139. + message.ByteSize())
  140. def MessageSetItemByteSize(field_number, msg):
  141. # First compute the sizes of the tags.
  142. # There are 2 tags for the beginning and ending of the repeated group, that
  143. # is field number 1, one with field number 2 (type_id) and one with field
  144. # number 3 (message).
  145. total_size = (2 * TagByteSize(1) + TagByteSize(2) + TagByteSize(3))
  146. # Add the number of bytes for type_id.
  147. total_size += _VarUInt64ByteSizeNoTag(field_number)
  148. message_size = msg.ByteSize()
  149. # The number of bytes for encoding the length of the message.
  150. total_size += _VarUInt64ByteSizeNoTag(message_size)
  151. # The size of the message.
  152. total_size += message_size
  153. return total_size
  154. def TagByteSize(field_number):
  155. """Returns the bytes required to serialize a tag with this field number."""
  156. # Just pass in type 0, since the type won't affect the tag+type size.
  157. return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0))
  158. # Private helper function for the *ByteSize() functions above.
  159. def _VarUInt64ByteSizeNoTag(uint64):
  160. """Returns the number of bytes required to serialize a single varint
  161. using boundary value comparisons. (unrolled loop optimization -WPierce)
  162. uint64 must be unsigned.
  163. """
  164. if uint64 <= 0x7f: return 1
  165. if uint64 <= 0x3fff: return 2
  166. if uint64 <= 0x1fffff: return 3
  167. if uint64 <= 0xfffffff: return 4
  168. if uint64 <= 0x7ffffffff: return 5
  169. if uint64 <= 0x3ffffffffff: return 6
  170. if uint64 <= 0x1ffffffffffff: return 7
  171. if uint64 <= 0xffffffffffffff: return 8
  172. if uint64 <= 0x7fffffffffffffff: return 9
  173. if uint64 > UINT64_MAX:
  174. raise message.EncodeError('Value out of range: %d' % uint64)
  175. return 10
  176. NON_PACKABLE_TYPES = (
  177. descriptor.FieldDescriptor.TYPE_STRING,
  178. descriptor.FieldDescriptor.TYPE_GROUP,
  179. descriptor.FieldDescriptor.TYPE_MESSAGE,
  180. descriptor.FieldDescriptor.TYPE_BYTES
  181. )
  182. def IsTypePackable(field_type):
  183. """Return true iff packable = true is valid for fields of this type.
  184. Args:
  185. field_type: a FieldDescriptor::Type value.
  186. Returns:
  187. True iff fields of this type are packable.
  188. """
  189. return field_type not in NON_PACKABLE_TYPES