decoder.py 36 KB

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