图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1067 lines
38 KiB

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