店播爬取Python脚本

decoder.py 38KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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. """Code for decoding protocol buffer primitives.
  31. This code is very similar to encoder.py -- read the docs for that module first.
  32. A "decoder" is a function with the signature:
  33. Decode(buffer, pos, end, message, field_dict)
  34. The arguments are:
  35. buffer: The string containing the encoded message.
  36. pos: The current position in the string.
  37. end: The position in the string where the current message ends. May be
  38. less than len(buffer) if we're reading a sub-message.
  39. message: The message object into which we're parsing.
  40. field_dict: message._fields (avoids a hashtable lookup).
  41. The decoder reads the field and stores it into field_dict, returning the new
  42. buffer position. A decoder for a repeated field may proactively decode all of
  43. the elements of that field, if they appear consecutively.
  44. Note that decoders may throw any of the following:
  45. IndexError: Indicates a truncated message.
  46. struct.error: Unpacking of a fixed-width field failed.
  47. message.DecodeError: Other errors.
  48. Decoders are expected to raise an exception if they are called with pos > end.
  49. This allows callers to be lax about bounds checking: it's fineto read past
  50. "end" as long as you are sure that someone else will notice and throw an
  51. exception later on.
  52. Something up the call stack is expected to catch IndexError and struct.error
  53. and convert them to message.DecodeError.
  54. Decoders are constructed using decoder constructors with the signature:
  55. MakeDecoder(field_number, is_repeated, is_packed, key, new_default)
  56. The arguments are:
  57. field_number: The field number of the field we want to decode.
  58. is_repeated: Is the field a repeated field? (bool)
  59. is_packed: Is the field a packed field? (bool)
  60. key: The key to use when looking up the field within field_dict.
  61. (This is actually the FieldDescriptor but nothing in this
  62. file should depend on that.)
  63. new_default: A function which takes a message object as a parameter and
  64. returns a new instance of the default value for this field.
  65. (This is called for repeated fields and sub-messages, when an
  66. instance does not already exist.)
  67. As with encoders, we define a decoder constructor for every type of field.
  68. Then, for every field of every message class we construct an actual decoder.
  69. That decoder goes into a dict indexed by tag, so when we decode a message
  70. we repeatedly read a tag, look up the corresponding decoder, and invoke it.
  71. """
  72. __author__ = 'kenton@google.com (Kenton Varda)'
  73. import struct
  74. import sys
  75. import six
  76. _UCS2_MAXUNICODE = 65535
  77. if six.PY3:
  78. long = int
  79. else:
  80. import re # pylint: disable=g-import-not-at-top
  81. _SURROGATE_PATTERN = re.compile(six.u(r'[\ud800-\udfff]'))
  82. from google.protobuf.internal import containers
  83. from google.protobuf.internal import encoder
  84. from google.protobuf.internal import wire_format
  85. from google.protobuf import message
  86. # This will overflow and thus become IEEE-754 "infinity". We would use
  87. # "float('inf')" but it doesn't work on Windows pre-Python-2.6.
  88. _POS_INF = 1e10000
  89. _NEG_INF = -_POS_INF
  90. _NAN = _POS_INF * 0
  91. # This is not for optimization, but rather to avoid conflicts with local
  92. # variables named "message".
  93. _DecodeError = message.DecodeError
  94. def _VarintDecoder(mask, result_type):
  95. """Return an encoder for a basic varint value (does not include tag).
  96. Decoded values will be bitwise-anded with the given mask before being
  97. returned, e.g. to limit them to 32 bits. The returned decoder does not
  98. take the usual "end" parameter -- the caller is expected to do bounds checking
  99. after the fact (often the caller can defer such checking until later). The
  100. decoder returns a (value, new_pos) pair.
  101. """
  102. def DecodeVarint(buffer, pos):
  103. result = 0
  104. shift = 0
  105. while 1:
  106. b = six.indexbytes(buffer, pos)
  107. result |= ((b & 0x7f) << shift)
  108. pos += 1
  109. if not (b & 0x80):
  110. result &= mask
  111. result = result_type(result)
  112. return (result, pos)
  113. shift += 7
  114. if shift >= 64:
  115. raise _DecodeError('Too many bytes when decoding varint.')
  116. return DecodeVarint
  117. def _SignedVarintDecoder(bits, result_type):
  118. """Like _VarintDecoder() but decodes signed values."""
  119. signbit = 1 << (bits - 1)
  120. mask = (1 << bits) - 1
  121. def DecodeVarint(buffer, pos):
  122. result = 0
  123. shift = 0
  124. while 1:
  125. b = six.indexbytes(buffer, pos)
  126. result |= ((b & 0x7f) << shift)
  127. pos += 1
  128. if not (b & 0x80):
  129. result &= mask
  130. result = (result ^ signbit) - signbit
  131. result = result_type(result)
  132. return (result, pos)
  133. shift += 7
  134. if shift >= 64:
  135. raise _DecodeError('Too many bytes when decoding varint.')
  136. return DecodeVarint
  137. # We force 32-bit values to int and 64-bit values to long to make
  138. # alternate implementations where the distinction is more significant
  139. # (e.g. the C++ implementation) simpler.
  140. _DecodeVarint = _VarintDecoder((1 << 64) - 1, long)
  141. _DecodeSignedVarint = _SignedVarintDecoder(64, long)
  142. # Use these versions for values which must be limited to 32 bits.
  143. _DecodeVarint32 = _VarintDecoder((1 << 32) - 1, int)
  144. _DecodeSignedVarint32 = _SignedVarintDecoder(32, int)
  145. def ReadTag(buffer, pos):
  146. """Read a tag from the memoryview, and return a (tag_bytes, new_pos) tuple.
  147. We return the raw bytes of the tag rather than decoding them. The raw
  148. bytes can then be used to look up the proper decoder. This effectively allows
  149. us to trade some work that would be done in pure-python (decoding a varint)
  150. for work that is done in C (searching for a byte string in a hash table).
  151. In a low-level language it would be much cheaper to decode the varint and
  152. use that, but not in Python.
  153. Args:
  154. buffer: memoryview object of the encoded bytes
  155. pos: int of the current position to start from
  156. Returns:
  157. Tuple[bytes, int] of the tag data and new position.
  158. """
  159. start = pos
  160. while six.indexbytes(buffer, pos) & 0x80:
  161. pos += 1
  162. pos += 1
  163. tag_bytes = buffer[start:pos].tobytes()
  164. return tag_bytes, pos
  165. # --------------------------------------------------------------------
  166. def _SimpleDecoder(wire_type, decode_value):
  167. """Return a constructor for a decoder for fields of a particular type.
  168. Args:
  169. wire_type: The field's wire type.
  170. decode_value: A function which decodes an individual value, e.g.
  171. _DecodeVarint()
  172. """
  173. def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default,
  174. clear_if_default=False):
  175. if is_packed:
  176. local_DecodeVarint = _DecodeVarint
  177. def DecodePackedField(buffer, pos, end, message, field_dict):
  178. value = field_dict.get(key)
  179. if value is None:
  180. value = field_dict.setdefault(key, new_default(message))
  181. (endpoint, pos) = local_DecodeVarint(buffer, pos)
  182. endpoint += pos
  183. if endpoint > end:
  184. raise _DecodeError('Truncated message.')
  185. while pos < endpoint:
  186. (element, pos) = decode_value(buffer, pos)
  187. value.append(element)
  188. if pos > endpoint:
  189. del value[-1] # Discard corrupt value.
  190. raise _DecodeError('Packed element was truncated.')
  191. return pos
  192. return DecodePackedField
  193. elif is_repeated:
  194. tag_bytes = encoder.TagBytes(field_number, wire_type)
  195. tag_len = len(tag_bytes)
  196. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  197. value = field_dict.get(key)
  198. if value is None:
  199. value = field_dict.setdefault(key, new_default(message))
  200. while 1:
  201. (element, new_pos) = decode_value(buffer, pos)
  202. value.append(element)
  203. # Predict that the next tag is another copy of the same repeated
  204. # field.
  205. pos = new_pos + tag_len
  206. if buffer[new_pos:pos] != tag_bytes or new_pos >= end:
  207. # Prediction failed. Return.
  208. if new_pos > end:
  209. raise _DecodeError('Truncated message.')
  210. return new_pos
  211. return DecodeRepeatedField
  212. else:
  213. def DecodeField(buffer, pos, end, message, field_dict):
  214. (new_value, pos) = decode_value(buffer, pos)
  215. if pos > end:
  216. raise _DecodeError('Truncated message.')
  217. if clear_if_default and not new_value:
  218. field_dict.pop(key, None)
  219. else:
  220. field_dict[key] = new_value
  221. return pos
  222. return DecodeField
  223. return SpecificDecoder
  224. def _ModifiedDecoder(wire_type, decode_value, modify_value):
  225. """Like SimpleDecoder but additionally invokes modify_value on every value
  226. before storing it. Usually modify_value is ZigZagDecode.
  227. """
  228. # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
  229. # not enough to make a significant difference.
  230. def InnerDecode(buffer, pos):
  231. (result, new_pos) = decode_value(buffer, pos)
  232. return (modify_value(result), new_pos)
  233. return _SimpleDecoder(wire_type, InnerDecode)
  234. def _StructPackDecoder(wire_type, format):
  235. """Return a constructor for a decoder for a fixed-width field.
  236. Args:
  237. wire_type: The field's wire type.
  238. format: The format string to pass to struct.unpack().
  239. """
  240. value_size = struct.calcsize(format)
  241. local_unpack = struct.unpack
  242. # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
  243. # not enough to make a significant difference.
  244. # Note that we expect someone up-stack to catch struct.error and convert
  245. # it to _DecodeError -- this way we don't have to set up exception-
  246. # handling blocks every time we parse one value.
  247. def InnerDecode(buffer, pos):
  248. new_pos = pos + value_size
  249. result = local_unpack(format, buffer[pos:new_pos])[0]
  250. return (result, new_pos)
  251. return _SimpleDecoder(wire_type, InnerDecode)
  252. def _FloatDecoder():
  253. """Returns a decoder for a float field.
  254. This code works around a bug in struct.unpack for non-finite 32-bit
  255. floating-point values.
  256. """
  257. local_unpack = struct.unpack
  258. def InnerDecode(buffer, pos):
  259. """Decode serialized float to a float and new position.
  260. Args:
  261. buffer: memoryview of the serialized bytes
  262. pos: int, position in the memory view to start at.
  263. Returns:
  264. Tuple[float, int] of the deserialized float value and new position
  265. in the serialized data.
  266. """
  267. # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign
  268. # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand.
  269. new_pos = pos + 4
  270. float_bytes = buffer[pos:new_pos].tobytes()
  271. # If this value has all its exponent bits set, then it's non-finite.
  272. # In Python 2.4, struct.unpack will convert it to a finite 64-bit value.
  273. # To avoid that, we parse it specially.
  274. if (float_bytes[3:4] in b'\x7F\xFF' and float_bytes[2:3] >= b'\x80'):
  275. # If at least one significand bit is set...
  276. if float_bytes[0:3] != b'\x00\x00\x80':
  277. return (_NAN, new_pos)
  278. # If sign bit is set...
  279. if float_bytes[3:4] == b'\xFF':
  280. return (_NEG_INF, new_pos)
  281. return (_POS_INF, new_pos)
  282. # Note that we expect someone up-stack to catch struct.error and convert
  283. # it to _DecodeError -- this way we don't have to set up exception-
  284. # handling blocks every time we parse one value.
  285. result = local_unpack('<f', float_bytes)[0]
  286. return (result, new_pos)
  287. return _SimpleDecoder(wire_format.WIRETYPE_FIXED32, InnerDecode)
  288. def _DoubleDecoder():
  289. """Returns a decoder for a double field.
  290. This code works around a bug in struct.unpack for not-a-number.
  291. """
  292. local_unpack = struct.unpack
  293. def InnerDecode(buffer, pos):
  294. """Decode serialized double to a double and new position.
  295. Args:
  296. buffer: memoryview of the serialized bytes.
  297. pos: int, position in the memory view to start at.
  298. Returns:
  299. Tuple[float, int] of the decoded double value and new position
  300. in the serialized data.
  301. """
  302. # We expect a 64-bit value in little-endian byte order. Bit 1 is the sign
  303. # bit, bits 2-12 represent the exponent, and bits 13-64 are the significand.
  304. new_pos = pos + 8
  305. double_bytes = buffer[pos:new_pos].tobytes()
  306. # If this value has all its exponent bits set and at least one significand
  307. # bit set, it's not a number. In Python 2.4, struct.unpack will treat it
  308. # as inf or -inf. To avoid that, we treat it specially.
  309. if ((double_bytes[7:8] in b'\x7F\xFF')
  310. and (double_bytes[6:7] >= b'\xF0')
  311. and (double_bytes[0:7] != b'\x00\x00\x00\x00\x00\x00\xF0')):
  312. return (_NAN, new_pos)
  313. # Note that we expect someone up-stack to catch struct.error and convert
  314. # it to _DecodeError -- this way we don't have to set up exception-
  315. # handling blocks every time we parse one value.
  316. result = local_unpack('<d', double_bytes)[0]
  317. return (result, new_pos)
  318. return _SimpleDecoder(wire_format.WIRETYPE_FIXED64, InnerDecode)
  319. def EnumDecoder(field_number, is_repeated, is_packed, key, new_default,
  320. clear_if_default=False):
  321. """Returns a decoder for enum field."""
  322. enum_type = key.enum_type
  323. if is_packed:
  324. local_DecodeVarint = _DecodeVarint
  325. def DecodePackedField(buffer, pos, end, message, field_dict):
  326. """Decode serialized packed enum to its value and a new position.
  327. Args:
  328. buffer: memoryview of the serialized bytes.
  329. pos: int, position in the memory view to start at.
  330. end: int, end position of serialized data
  331. message: Message object to store unknown fields in
  332. field_dict: Map[Descriptor, Any] to store decoded values in.
  333. Returns:
  334. int, new position in serialized data.
  335. """
  336. value = field_dict.get(key)
  337. if value is None:
  338. value = field_dict.setdefault(key, new_default(message))
  339. (endpoint, pos) = local_DecodeVarint(buffer, pos)
  340. endpoint += pos
  341. if endpoint > end:
  342. raise _DecodeError('Truncated message.')
  343. while pos < endpoint:
  344. value_start_pos = pos
  345. (element, pos) = _DecodeSignedVarint32(buffer, pos)
  346. # pylint: disable=protected-access
  347. if element in enum_type.values_by_number:
  348. value.append(element)
  349. else:
  350. if not message._unknown_fields:
  351. message._unknown_fields = []
  352. tag_bytes = encoder.TagBytes(field_number,
  353. wire_format.WIRETYPE_VARINT)
  354. message._unknown_fields.append(
  355. (tag_bytes, buffer[value_start_pos:pos].tobytes()))
  356. if message._unknown_field_set is None:
  357. message._unknown_field_set = containers.UnknownFieldSet()
  358. message._unknown_field_set._add(
  359. field_number, wire_format.WIRETYPE_VARINT, element)
  360. # pylint: enable=protected-access
  361. if pos > endpoint:
  362. if element in enum_type.values_by_number:
  363. del value[-1] # Discard corrupt value.
  364. else:
  365. del message._unknown_fields[-1]
  366. # pylint: disable=protected-access
  367. del message._unknown_field_set._values[-1]
  368. # pylint: enable=protected-access
  369. raise _DecodeError('Packed element was truncated.')
  370. return pos
  371. return DecodePackedField
  372. elif is_repeated:
  373. tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_VARINT)
  374. tag_len = len(tag_bytes)
  375. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  376. """Decode serialized repeated enum to its value and a new position.
  377. Args:
  378. buffer: memoryview of the serialized bytes.
  379. pos: int, position in the memory view to start at.
  380. end: int, end position of serialized data
  381. message: Message object to store unknown fields in
  382. field_dict: Map[Descriptor, Any] to store decoded values in.
  383. Returns:
  384. int, new position in serialized data.
  385. """
  386. value = field_dict.get(key)
  387. if value is None:
  388. value = field_dict.setdefault(key, new_default(message))
  389. while 1:
  390. (element, new_pos) = _DecodeSignedVarint32(buffer, pos)
  391. # pylint: disable=protected-access
  392. if element in enum_type.values_by_number:
  393. value.append(element)
  394. else:
  395. if not message._unknown_fields:
  396. message._unknown_fields = []
  397. message._unknown_fields.append(
  398. (tag_bytes, buffer[pos:new_pos].tobytes()))
  399. if message._unknown_field_set is None:
  400. message._unknown_field_set = containers.UnknownFieldSet()
  401. message._unknown_field_set._add(
  402. field_number, wire_format.WIRETYPE_VARINT, element)
  403. # pylint: enable=protected-access
  404. # Predict that the next tag is another copy of the same repeated
  405. # field.
  406. pos = new_pos + tag_len
  407. if buffer[new_pos:pos] != tag_bytes or new_pos >= end:
  408. # Prediction failed. Return.
  409. if new_pos > end:
  410. raise _DecodeError('Truncated message.')
  411. return new_pos
  412. return DecodeRepeatedField
  413. else:
  414. def DecodeField(buffer, pos, end, message, field_dict):
  415. """Decode serialized repeated enum to its value and a new position.
  416. Args:
  417. buffer: memoryview of the serialized bytes.
  418. pos: int, position in the memory view to start at.
  419. end: int, end position of serialized data
  420. message: Message object to store unknown fields in
  421. field_dict: Map[Descriptor, Any] to store decoded values in.
  422. Returns:
  423. int, new position in serialized data.
  424. """
  425. value_start_pos = pos
  426. (enum_value, pos) = _DecodeSignedVarint32(buffer, pos)
  427. if pos > end:
  428. raise _DecodeError('Truncated message.')
  429. if clear_if_default and not enum_value:
  430. field_dict.pop(key, None)
  431. return pos
  432. # pylint: disable=protected-access
  433. if enum_value in enum_type.values_by_number:
  434. field_dict[key] = enum_value
  435. else:
  436. if not message._unknown_fields:
  437. message._unknown_fields = []
  438. tag_bytes = encoder.TagBytes(field_number,
  439. wire_format.WIRETYPE_VARINT)
  440. message._unknown_fields.append(
  441. (tag_bytes, buffer[value_start_pos:pos].tobytes()))
  442. if message._unknown_field_set is None:
  443. message._unknown_field_set = containers.UnknownFieldSet()
  444. message._unknown_field_set._add(
  445. field_number, wire_format.WIRETYPE_VARINT, enum_value)
  446. # pylint: enable=protected-access
  447. return pos
  448. return DecodeField
  449. # --------------------------------------------------------------------
  450. Int32Decoder = _SimpleDecoder(
  451. wire_format.WIRETYPE_VARINT, _DecodeSignedVarint32)
  452. Int64Decoder = _SimpleDecoder(
  453. wire_format.WIRETYPE_VARINT, _DecodeSignedVarint)
  454. UInt32Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint32)
  455. UInt64Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint)
  456. SInt32Decoder = _ModifiedDecoder(
  457. wire_format.WIRETYPE_VARINT, _DecodeVarint32, wire_format.ZigZagDecode)
  458. SInt64Decoder = _ModifiedDecoder(
  459. wire_format.WIRETYPE_VARINT, _DecodeVarint, wire_format.ZigZagDecode)
  460. # Note that Python conveniently guarantees that when using the '<' prefix on
  461. # formats, they will also have the same size across all platforms (as opposed
  462. # to without the prefix, where their sizes depend on the C compiler's basic
  463. # type sizes).
  464. Fixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, '<I')
  465. Fixed64Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED64, '<Q')
  466. SFixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, '<i')
  467. SFixed64Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED64, '<q')
  468. FloatDecoder = _FloatDecoder()
  469. DoubleDecoder = _DoubleDecoder()
  470. BoolDecoder = _ModifiedDecoder(
  471. wire_format.WIRETYPE_VARINT, _DecodeVarint, bool)
  472. def StringDecoder(field_number, is_repeated, is_packed, key, new_default,
  473. is_strict_utf8=False, clear_if_default=False):
  474. """Returns a decoder for a string field."""
  475. local_DecodeVarint = _DecodeVarint
  476. local_unicode = six.text_type
  477. def _ConvertToUnicode(memview):
  478. """Convert byte to unicode."""
  479. byte_str = memview.tobytes()
  480. try:
  481. value = local_unicode(byte_str, 'utf-8')
  482. except UnicodeDecodeError as e:
  483. # add more information to the error message and re-raise it.
  484. e.reason = '%s in field: %s' % (e, key.full_name)
  485. raise
  486. if is_strict_utf8 and six.PY2 and sys.maxunicode > _UCS2_MAXUNICODE:
  487. # Only do the check for python2 ucs4 when is_strict_utf8 enabled
  488. if _SURROGATE_PATTERN.search(value):
  489. reason = ('String field %s contains invalid UTF-8 data when parsing'
  490. 'a protocol buffer: surrogates not allowed. Use'
  491. 'the bytes type if you intend to send raw bytes.') % (
  492. key.full_name)
  493. raise message.DecodeError(reason)
  494. return value
  495. assert not is_packed
  496. if is_repeated:
  497. tag_bytes = encoder.TagBytes(field_number,
  498. wire_format.WIRETYPE_LENGTH_DELIMITED)
  499. tag_len = len(tag_bytes)
  500. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  501. value = field_dict.get(key)
  502. if value is None:
  503. value = field_dict.setdefault(key, new_default(message))
  504. while 1:
  505. (size, pos) = local_DecodeVarint(buffer, pos)
  506. new_pos = pos + size
  507. if new_pos > end:
  508. raise _DecodeError('Truncated string.')
  509. value.append(_ConvertToUnicode(buffer[pos:new_pos]))
  510. # Predict that the next tag is another copy of the same repeated field.
  511. pos = new_pos + tag_len
  512. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  513. # Prediction failed. Return.
  514. return new_pos
  515. return DecodeRepeatedField
  516. else:
  517. def DecodeField(buffer, pos, end, message, field_dict):
  518. (size, pos) = local_DecodeVarint(buffer, pos)
  519. new_pos = pos + size
  520. if new_pos > end:
  521. raise _DecodeError('Truncated string.')
  522. if clear_if_default and not size:
  523. field_dict.pop(key, None)
  524. else:
  525. field_dict[key] = _ConvertToUnicode(buffer[pos:new_pos])
  526. return new_pos
  527. return DecodeField
  528. def BytesDecoder(field_number, is_repeated, is_packed, key, new_default,
  529. clear_if_default=False):
  530. """Returns a decoder for a bytes field."""
  531. local_DecodeVarint = _DecodeVarint
  532. assert not is_packed
  533. if is_repeated:
  534. tag_bytes = encoder.TagBytes(field_number,
  535. wire_format.WIRETYPE_LENGTH_DELIMITED)
  536. tag_len = len(tag_bytes)
  537. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  538. value = field_dict.get(key)
  539. if value is None:
  540. value = field_dict.setdefault(key, new_default(message))
  541. while 1:
  542. (size, pos) = local_DecodeVarint(buffer, pos)
  543. new_pos = pos + size
  544. if new_pos > end:
  545. raise _DecodeError('Truncated string.')
  546. value.append(buffer[pos:new_pos].tobytes())
  547. # Predict that the next tag is another copy of the same repeated field.
  548. pos = new_pos + tag_len
  549. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  550. # Prediction failed. Return.
  551. return new_pos
  552. return DecodeRepeatedField
  553. else:
  554. def DecodeField(buffer, pos, end, message, field_dict):
  555. (size, pos) = local_DecodeVarint(buffer, pos)
  556. new_pos = pos + size
  557. if new_pos > end:
  558. raise _DecodeError('Truncated string.')
  559. if clear_if_default and not size:
  560. field_dict.pop(key, None)
  561. else:
  562. field_dict[key] = buffer[pos:new_pos].tobytes()
  563. return new_pos
  564. return DecodeField
  565. def GroupDecoder(field_number, is_repeated, is_packed, key, new_default):
  566. """Returns a decoder for a group field."""
  567. end_tag_bytes = encoder.TagBytes(field_number,
  568. wire_format.WIRETYPE_END_GROUP)
  569. end_tag_len = len(end_tag_bytes)
  570. assert not is_packed
  571. if is_repeated:
  572. tag_bytes = encoder.TagBytes(field_number,
  573. wire_format.WIRETYPE_START_GROUP)
  574. tag_len = len(tag_bytes)
  575. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  576. value = field_dict.get(key)
  577. if value is None:
  578. value = field_dict.setdefault(key, new_default(message))
  579. while 1:
  580. value = field_dict.get(key)
  581. if value is None:
  582. value = field_dict.setdefault(key, new_default(message))
  583. # Read sub-message.
  584. pos = value.add()._InternalParse(buffer, pos, end)
  585. # Read end tag.
  586. new_pos = pos+end_tag_len
  587. if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:
  588. raise _DecodeError('Missing group end tag.')
  589. # Predict that the next tag is another copy of the same repeated field.
  590. pos = new_pos + tag_len
  591. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  592. # Prediction failed. Return.
  593. return new_pos
  594. return DecodeRepeatedField
  595. else:
  596. def DecodeField(buffer, pos, end, message, field_dict):
  597. value = field_dict.get(key)
  598. if value is None:
  599. value = field_dict.setdefault(key, new_default(message))
  600. # Read sub-message.
  601. pos = value._InternalParse(buffer, pos, end)
  602. # Read end tag.
  603. new_pos = pos+end_tag_len
  604. if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:
  605. raise _DecodeError('Missing group end tag.')
  606. return new_pos
  607. return DecodeField
  608. def MessageDecoder(field_number, is_repeated, is_packed, key, new_default):
  609. """Returns a decoder for a message field."""
  610. local_DecodeVarint = _DecodeVarint
  611. assert not is_packed
  612. if is_repeated:
  613. tag_bytes = encoder.TagBytes(field_number,
  614. wire_format.WIRETYPE_LENGTH_DELIMITED)
  615. tag_len = len(tag_bytes)
  616. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  617. value = field_dict.get(key)
  618. if value is None:
  619. value = field_dict.setdefault(key, new_default(message))
  620. while 1:
  621. # Read length.
  622. (size, pos) = local_DecodeVarint(buffer, pos)
  623. new_pos = pos + size
  624. if new_pos > end:
  625. raise _DecodeError('Truncated message.')
  626. # Read sub-message.
  627. if value.add()._InternalParse(buffer, pos, new_pos) != new_pos:
  628. # The only reason _InternalParse would return early is if it
  629. # encountered an end-group tag.
  630. raise _DecodeError('Unexpected end-group tag.')
  631. # Predict that the next tag is another copy of the same repeated field.
  632. pos = new_pos + tag_len
  633. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  634. # Prediction failed. Return.
  635. return new_pos
  636. return DecodeRepeatedField
  637. else:
  638. def DecodeField(buffer, pos, end, message, field_dict):
  639. value = field_dict.get(key)
  640. if value is None:
  641. value = field_dict.setdefault(key, new_default(message))
  642. # Read length.
  643. (size, pos) = local_DecodeVarint(buffer, pos)
  644. new_pos = pos + size
  645. if new_pos > end:
  646. raise _DecodeError('Truncated message.')
  647. # Read sub-message.
  648. if value._InternalParse(buffer, pos, new_pos) != new_pos:
  649. # The only reason _InternalParse would return early is if it encountered
  650. # an end-group tag.
  651. raise _DecodeError('Unexpected end-group tag.')
  652. return new_pos
  653. return DecodeField
  654. # --------------------------------------------------------------------
  655. MESSAGE_SET_ITEM_TAG = encoder.TagBytes(1, wire_format.WIRETYPE_START_GROUP)
  656. def MessageSetItemDecoder(descriptor):
  657. """Returns a decoder for a MessageSet item.
  658. The parameter is the message Descriptor.
  659. The message set message looks like this:
  660. message MessageSet {
  661. repeated group Item = 1 {
  662. required int32 type_id = 2;
  663. required string message = 3;
  664. }
  665. }
  666. """
  667. type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT)
  668. message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)
  669. item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP)
  670. local_ReadTag = ReadTag
  671. local_DecodeVarint = _DecodeVarint
  672. local_SkipField = SkipField
  673. def DecodeItem(buffer, pos, end, message, field_dict):
  674. """Decode serialized message set to its value and new position.
  675. Args:
  676. buffer: memoryview of the serialized bytes.
  677. pos: int, position in the memory view to start at.
  678. end: int, end position of serialized data
  679. message: Message object to store unknown fields in
  680. field_dict: Map[Descriptor, Any] to store decoded values in.
  681. Returns:
  682. int, new position in serialized data.
  683. """
  684. message_set_item_start = pos
  685. type_id = -1
  686. message_start = -1
  687. message_end = -1
  688. # Technically, type_id and message can appear in any order, so we need
  689. # a little loop here.
  690. while 1:
  691. (tag_bytes, pos) = local_ReadTag(buffer, pos)
  692. if tag_bytes == type_id_tag_bytes:
  693. (type_id, pos) = local_DecodeVarint(buffer, pos)
  694. elif tag_bytes == message_tag_bytes:
  695. (size, message_start) = local_DecodeVarint(buffer, pos)
  696. pos = message_end = message_start + size
  697. elif tag_bytes == item_end_tag_bytes:
  698. break
  699. else:
  700. pos = SkipField(buffer, pos, end, tag_bytes)
  701. if pos == -1:
  702. raise _DecodeError('Missing group end tag.')
  703. if pos > end:
  704. raise _DecodeError('Truncated message.')
  705. if type_id == -1:
  706. raise _DecodeError('MessageSet item missing type_id.')
  707. if message_start == -1:
  708. raise _DecodeError('MessageSet item missing message.')
  709. extension = message.Extensions._FindExtensionByNumber(type_id)
  710. # pylint: disable=protected-access
  711. if extension is not None:
  712. value = field_dict.get(extension)
  713. if value is None:
  714. message_type = extension.message_type
  715. if not hasattr(message_type, '_concrete_class'):
  716. # pylint: disable=protected-access
  717. message._FACTORY.GetPrototype(message_type)
  718. value = field_dict.setdefault(
  719. extension, message_type._concrete_class())
  720. if value._InternalParse(buffer, message_start,message_end) != message_end:
  721. # The only reason _InternalParse would return early is if it encountered
  722. # an end-group tag.
  723. raise _DecodeError('Unexpected end-group tag.')
  724. else:
  725. if not message._unknown_fields:
  726. message._unknown_fields = []
  727. message._unknown_fields.append(
  728. (MESSAGE_SET_ITEM_TAG, buffer[message_set_item_start:pos].tobytes()))
  729. if message._unknown_field_set is None:
  730. message._unknown_field_set = containers.UnknownFieldSet()
  731. message._unknown_field_set._add(
  732. type_id,
  733. wire_format.WIRETYPE_LENGTH_DELIMITED,
  734. buffer[message_start:message_end].tobytes())
  735. # pylint: enable=protected-access
  736. return pos
  737. return DecodeItem
  738. # --------------------------------------------------------------------
  739. def MapDecoder(field_descriptor, new_default, is_message_map):
  740. """Returns a decoder for a map field."""
  741. key = field_descriptor
  742. tag_bytes = encoder.TagBytes(field_descriptor.number,
  743. wire_format.WIRETYPE_LENGTH_DELIMITED)
  744. tag_len = len(tag_bytes)
  745. local_DecodeVarint = _DecodeVarint
  746. # Can't read _concrete_class yet; might not be initialized.
  747. message_type = field_descriptor.message_type
  748. def DecodeMap(buffer, pos, end, message, field_dict):
  749. submsg = message_type._concrete_class()
  750. value = field_dict.get(key)
  751. if value is None:
  752. value = field_dict.setdefault(key, new_default(message))
  753. while 1:
  754. # Read length.
  755. (size, pos) = local_DecodeVarint(buffer, pos)
  756. new_pos = pos + size
  757. if new_pos > end:
  758. raise _DecodeError('Truncated message.')
  759. # Read sub-message.
  760. submsg.Clear()
  761. if submsg._InternalParse(buffer, pos, new_pos) != new_pos:
  762. # The only reason _InternalParse would return early is if it
  763. # encountered an end-group tag.
  764. raise _DecodeError('Unexpected end-group tag.')
  765. if is_message_map:
  766. value[submsg.key].CopyFrom(submsg.value)
  767. else:
  768. value[submsg.key] = submsg.value
  769. # Predict that the next tag is another copy of the same repeated field.
  770. pos = new_pos + tag_len
  771. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  772. # Prediction failed. Return.
  773. return new_pos
  774. return DecodeMap
  775. # --------------------------------------------------------------------
  776. # Optimization is not as heavy here because calls to SkipField() are rare,
  777. # except for handling end-group tags.
  778. def _SkipVarint(buffer, pos, end):
  779. """Skip a varint value. Returns the new position."""
  780. # Previously ord(buffer[pos]) raised IndexError when pos is out of range.
  781. # With this code, ord(b'') raises TypeError. Both are handled in
  782. # python_message.py to generate a 'Truncated message' error.
  783. while ord(buffer[pos:pos+1].tobytes()) & 0x80:
  784. pos += 1
  785. pos += 1
  786. if pos > end:
  787. raise _DecodeError('Truncated message.')
  788. return pos
  789. def _SkipFixed64(buffer, pos, end):
  790. """Skip a fixed64 value. Returns the new position."""
  791. pos += 8
  792. if pos > end:
  793. raise _DecodeError('Truncated message.')
  794. return pos
  795. def _DecodeFixed64(buffer, pos):
  796. """Decode a fixed64."""
  797. new_pos = pos + 8
  798. return (struct.unpack('<Q', buffer[pos:new_pos])[0], new_pos)
  799. def _SkipLengthDelimited(buffer, pos, end):
  800. """Skip a length-delimited value. Returns the new position."""
  801. (size, pos) = _DecodeVarint(buffer, pos)
  802. pos += size
  803. if pos > end:
  804. raise _DecodeError('Truncated message.')
  805. return pos
  806. def _SkipGroup(buffer, pos, end):
  807. """Skip sub-group. Returns the new position."""
  808. while 1:
  809. (tag_bytes, pos) = ReadTag(buffer, pos)
  810. new_pos = SkipField(buffer, pos, end, tag_bytes)
  811. if new_pos == -1:
  812. return pos
  813. pos = new_pos
  814. def _DecodeUnknownFieldSet(buffer, pos, end_pos=None):
  815. """Decode UnknownFieldSet. Returns the UnknownFieldSet and new position."""
  816. unknown_field_set = containers.UnknownFieldSet()
  817. while end_pos is None or pos < end_pos:
  818. (tag_bytes, pos) = ReadTag(buffer, pos)
  819. (tag, _) = _DecodeVarint(tag_bytes, 0)
  820. field_number, wire_type = wire_format.UnpackTag(tag)
  821. if wire_type == wire_format.WIRETYPE_END_GROUP:
  822. break
  823. (data, pos) = _DecodeUnknownField(buffer, pos, wire_type)
  824. # pylint: disable=protected-access
  825. unknown_field_set._add(field_number, wire_type, data)
  826. return (unknown_field_set, pos)
  827. def _DecodeUnknownField(buffer, pos, wire_type):
  828. """Decode a unknown field. Returns the UnknownField and new position."""
  829. if wire_type == wire_format.WIRETYPE_VARINT:
  830. (data, pos) = _DecodeVarint(buffer, pos)
  831. elif wire_type == wire_format.WIRETYPE_FIXED64:
  832. (data, pos) = _DecodeFixed64(buffer, pos)
  833. elif wire_type == wire_format.WIRETYPE_FIXED32:
  834. (data, pos) = _DecodeFixed32(buffer, pos)
  835. elif wire_type == wire_format.WIRETYPE_LENGTH_DELIMITED:
  836. (size, pos) = _DecodeVarint(buffer, pos)
  837. data = buffer[pos:pos+size].tobytes()
  838. pos += size
  839. elif wire_type == wire_format.WIRETYPE_START_GROUP:
  840. (data, pos) = _DecodeUnknownFieldSet(buffer, pos)
  841. elif wire_type == wire_format.WIRETYPE_END_GROUP:
  842. return (0, -1)
  843. else:
  844. raise _DecodeError('Wrong wire type in tag.')
  845. return (data, pos)
  846. def _EndGroup(buffer, pos, end):
  847. """Skipping an END_GROUP tag returns -1 to tell the parent loop to break."""
  848. return -1
  849. def _SkipFixed32(buffer, pos, end):
  850. """Skip a fixed32 value. Returns the new position."""
  851. pos += 4
  852. if pos > end:
  853. raise _DecodeError('Truncated message.')
  854. return pos
  855. def _DecodeFixed32(buffer, pos):
  856. """Decode a fixed32."""
  857. new_pos = pos + 4
  858. return (struct.unpack('<I', buffer[pos:new_pos])[0], new_pos)
  859. def _RaiseInvalidWireType(buffer, pos, end):
  860. """Skip function for unknown wire types. Raises an exception."""
  861. raise _DecodeError('Tag had invalid wire type.')
  862. def _FieldSkipper():
  863. """Constructs the SkipField function."""
  864. WIRETYPE_TO_SKIPPER = [
  865. _SkipVarint,
  866. _SkipFixed64,
  867. _SkipLengthDelimited,
  868. _SkipGroup,
  869. _EndGroup,
  870. _SkipFixed32,
  871. _RaiseInvalidWireType,
  872. _RaiseInvalidWireType,
  873. ]
  874. wiretype_mask = wire_format.TAG_TYPE_MASK
  875. def SkipField(buffer, pos, end, tag_bytes):
  876. """Skips a field with the specified tag.
  877. |pos| should point to the byte immediately after the tag.
  878. Returns:
  879. The new position (after the tag value), or -1 if the tag is an end-group
  880. tag (in which case the calling loop should break).
  881. """
  882. # The wire type is always in the first byte since varints are little-endian.
  883. wire_type = ord(tag_bytes[0:1]) & wiretype_mask
  884. return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)
  885. return SkipField
  886. SkipField = _FieldSkipper()