decoder.py 37 KB

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