decoder.py 37 KB

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