decoder.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Code for decoding protocol buffer primitives.
  31. This code is very similar to encoder.py -- read the docs for that module first.
  32. A "decoder" is a function with the signature:
  33. Decode(buffer, pos, end, message, field_dict)
  34. The arguments are:
  35. buffer: The string containing the encoded message.
  36. pos: The current position in the string.
  37. end: The position in the string where the current message ends. May be
  38. less than len(buffer) if we're reading a sub-message.
  39. message: The message object into which we're parsing.
  40. field_dict: message._fields (avoids a hashtable lookup).
  41. The decoder reads the field and stores it into field_dict, returning the new
  42. buffer position. A decoder for a repeated field may proactively decode all of
  43. the elements of that field, if they appear consecutively.
  44. Note that decoders may throw any of the following:
  45. IndexError: Indicates a truncated message.
  46. struct.error: Unpacking of a fixed-width field failed.
  47. message.DecodeError: Other errors.
  48. Decoders are expected to raise an exception if they are called with pos > end.
  49. This allows callers to be lax about bounds checking: it's fineto read past
  50. "end" as long as you are sure that someone else will notice and throw an
  51. exception later on.
  52. Something up the call stack is expected to catch IndexError and struct.error
  53. and convert them to message.DecodeError.
  54. Decoders are constructed using decoder constructors with the signature:
  55. MakeDecoder(field_number, is_repeated, is_packed, key, new_default)
  56. The arguments are:
  57. field_number: The field number of the field we want to decode.
  58. is_repeated: Is the field a repeated field? (bool)
  59. is_packed: Is the field a packed field? (bool)
  60. key: The key to use when looking up the field within field_dict.
  61. (This is actually the FieldDescriptor but nothing in this
  62. file should depend on that.)
  63. new_default: A function which takes a message object as a parameter and
  64. returns a new instance of the default value for this field.
  65. (This is called for repeated fields and sub-messages, when an
  66. instance does not already exist.)
  67. As with encoders, we define a decoder constructor for every type of field.
  68. Then, for every field of every message class we construct an actual decoder.
  69. That decoder goes into a dict indexed by tag, so when we decode a message
  70. we repeatedly read a tag, look up the corresponding decoder, and invoke it.
  71. """
  72. __author__ = 'kenton@google.com (Kenton Varda)'
  73. import struct
  74. import six
  75. if six.PY3:
  76. long = int
  77. from google.protobuf.internal import encoder
  78. from google.protobuf.internal import wire_format
  79. from google.protobuf import message
  80. # This will overflow and thus become IEEE-754 "infinity". We would use
  81. # "float('inf')" but it doesn't work on Windows pre-Python-2.6.
  82. _POS_INF = 1e10000
  83. _NEG_INF = -_POS_INF
  84. _NAN = _POS_INF * 0
  85. # This is not for optimization, but rather to avoid conflicts with local
  86. # variables named "message".
  87. _DecodeError = message.DecodeError
  88. def _VarintDecoder(mask, result_type):
  89. """Return an encoder for a basic varint value (does not include tag).
  90. Decoded values will be bitwise-anded with the given mask before being
  91. returned, e.g. to limit them to 32 bits. The returned decoder does not
  92. take the usual "end" parameter -- the caller is expected to do bounds checking
  93. after the fact (often the caller can defer such checking until later). The
  94. decoder returns a (value, new_pos) pair.
  95. """
  96. def DecodeVarint(buffer, pos):
  97. result = 0
  98. shift = 0
  99. while 1:
  100. b = six.indexbytes(buffer, pos)
  101. result |= ((b & 0x7f) << shift)
  102. pos += 1
  103. if not (b & 0x80):
  104. result &= mask
  105. result = result_type(result)
  106. return (result, pos)
  107. shift += 7
  108. if shift >= 64:
  109. raise _DecodeError('Too many bytes when decoding varint.')
  110. return DecodeVarint
  111. def _SignedVarintDecoder(bits, result_type):
  112. """Like _VarintDecoder() but decodes signed values."""
  113. signbit = 1 << (bits - 1)
  114. mask = (1 << bits) - 1
  115. def DecodeVarint(buffer, pos):
  116. result = 0
  117. shift = 0
  118. while 1:
  119. b = six.indexbytes(buffer, pos)
  120. result |= ((b & 0x7f) << shift)
  121. pos += 1
  122. if not (b & 0x80):
  123. result &= mask
  124. result = (result ^ signbit) - signbit
  125. result = result_type(result)
  126. return (result, pos)
  127. shift += 7
  128. if shift >= 64:
  129. raise _DecodeError('Too many bytes when decoding varint.')
  130. return DecodeVarint
  131. # We force 32-bit values to int and 64-bit values to long to make
  132. # alternate implementations where the distinction is more significant
  133. # (e.g. the C++ implementation) simpler.
  134. _DecodeVarint = _VarintDecoder((1 << 64) - 1, long)
  135. _DecodeSignedVarint = _SignedVarintDecoder(64, long)
  136. # Use these versions for values which must be limited to 32 bits.
  137. _DecodeVarint32 = _VarintDecoder((1 << 32) - 1, int)
  138. _DecodeSignedVarint32 = _SignedVarintDecoder(32, int)
  139. def ReadTag(buffer, pos):
  140. """Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
  141. We return the raw bytes of the tag rather than decoding them. The raw
  142. bytes can then be used to look up the proper decoder. This effectively allows
  143. us to trade some work that would be done in pure-python (decoding a varint)
  144. for work that is done in C (searching for a byte string in a hash table).
  145. In a low-level language it would be much cheaper to decode the varint and
  146. use that, but not in Python.
  147. """
  148. start = pos
  149. while six.indexbytes(buffer, pos) & 0x80:
  150. pos += 1
  151. pos += 1
  152. return (buffer[start:pos], pos)
  153. # --------------------------------------------------------------------
  154. def _SimpleDecoder(wire_type, decode_value):
  155. """Return a constructor for a decoder for fields of a particular type.
  156. Args:
  157. wire_type: The field's wire type.
  158. decode_value: A function which decodes an individual value, e.g.
  159. _DecodeVarint()
  160. """
  161. def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default):
  162. if is_packed:
  163. local_DecodeVarint = _DecodeVarint
  164. def DecodePackedField(buffer, pos, end, message, field_dict):
  165. value = field_dict.get(key)
  166. if value is None:
  167. value = field_dict.setdefault(key, new_default(message))
  168. (endpoint, pos) = local_DecodeVarint(buffer, pos)
  169. endpoint += pos
  170. if endpoint > end:
  171. raise _DecodeError('Truncated message.')
  172. while pos < endpoint:
  173. (element, pos) = decode_value(buffer, pos)
  174. value.append(element)
  175. if pos > endpoint:
  176. del value[-1] # Discard corrupt value.
  177. raise _DecodeError('Packed element was truncated.')
  178. return pos
  179. return DecodePackedField
  180. elif is_repeated:
  181. tag_bytes = encoder.TagBytes(field_number, wire_type)
  182. tag_len = len(tag_bytes)
  183. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  184. value = field_dict.get(key)
  185. if value is None:
  186. value = field_dict.setdefault(key, new_default(message))
  187. while 1:
  188. (element, new_pos) = decode_value(buffer, pos)
  189. value.append(element)
  190. # Predict that the next tag is another copy of the same repeated
  191. # field.
  192. pos = new_pos + tag_len
  193. if buffer[new_pos:pos] != tag_bytes or new_pos >= end:
  194. # Prediction failed. Return.
  195. if new_pos > end:
  196. raise _DecodeError('Truncated message.')
  197. return new_pos
  198. return DecodeRepeatedField
  199. else:
  200. def DecodeField(buffer, pos, end, message, field_dict):
  201. (field_dict[key], pos) = decode_value(buffer, pos)
  202. if pos > end:
  203. del field_dict[key] # Discard corrupt value.
  204. raise _DecodeError('Truncated message.')
  205. return pos
  206. return DecodeField
  207. return SpecificDecoder
  208. def _ModifiedDecoder(wire_type, decode_value, modify_value):
  209. """Like SimpleDecoder but additionally invokes modify_value on every value
  210. before storing it. Usually modify_value is ZigZagDecode.
  211. """
  212. # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
  213. # not enough to make a significant difference.
  214. def InnerDecode(buffer, pos):
  215. (result, new_pos) = decode_value(buffer, pos)
  216. return (modify_value(result), new_pos)
  217. return _SimpleDecoder(wire_type, InnerDecode)
  218. def _StructPackDecoder(wire_type, format):
  219. """Return a constructor for a decoder for a fixed-width field.
  220. Args:
  221. wire_type: The field's wire type.
  222. format: The format string to pass to struct.unpack().
  223. """
  224. value_size = struct.calcsize(format)
  225. local_unpack = struct.unpack
  226. # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
  227. # not enough to make a significant difference.
  228. # Note that we expect someone up-stack to catch struct.error and convert
  229. # it to _DecodeError -- this way we don't have to set up exception-
  230. # handling blocks every time we parse one value.
  231. def InnerDecode(buffer, pos):
  232. new_pos = pos + value_size
  233. result = local_unpack(format, buffer[pos:new_pos])[0]
  234. return (result, new_pos)
  235. return _SimpleDecoder(wire_type, InnerDecode)
  236. def _FloatDecoder():
  237. """Returns a decoder for a float field.
  238. This code works around a bug in struct.unpack for non-finite 32-bit
  239. floating-point values.
  240. """
  241. local_unpack = struct.unpack
  242. def InnerDecode(buffer, pos):
  243. # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign
  244. # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand.
  245. new_pos = pos + 4
  246. float_bytes = buffer[pos:new_pos]
  247. # If this value has all its exponent bits set, then it's non-finite.
  248. # In Python 2.4, struct.unpack will convert it to a finite 64-bit value.
  249. # To avoid that, we parse it specially.
  250. if (float_bytes[3:4] in b'\x7F\xFF' and float_bytes[2:3] >= b'\x80'):
  251. # If at least one significand bit is set...
  252. if float_bytes[0:3] != b'\x00\x00\x80':
  253. return (_NAN, new_pos)
  254. # If sign bit is set...
  255. if float_bytes[3:4] == b'\xFF':
  256. return (_NEG_INF, new_pos)
  257. return (_POS_INF, new_pos)
  258. # Note that we expect someone up-stack to catch struct.error and convert
  259. # it to _DecodeError -- this way we don't have to set up exception-
  260. # handling blocks every time we parse one value.
  261. result = local_unpack('<f', float_bytes)[0]
  262. return (result, new_pos)
  263. return _SimpleDecoder(wire_format.WIRETYPE_FIXED32, InnerDecode)
  264. def _DoubleDecoder():
  265. """Returns a decoder for a double field.
  266. This code works around a bug in struct.unpack for not-a-number.
  267. """
  268. local_unpack = struct.unpack
  269. def InnerDecode(buffer, pos):
  270. # We expect a 64-bit value in little-endian byte order. Bit 1 is the sign
  271. # bit, bits 2-12 represent the exponent, and bits 13-64 are the significand.
  272. new_pos = pos + 8
  273. double_bytes = buffer[pos:new_pos]
  274. # If this value has all its exponent bits set and at least one significand
  275. # bit set, it's not a number. In Python 2.4, struct.unpack will treat it
  276. # as inf or -inf. To avoid that, we treat it specially.
  277. if ((double_bytes[7:8] in b'\x7F\xFF')
  278. and (double_bytes[6:7] >= b'\xF0')
  279. and (double_bytes[0:7] != b'\x00\x00\x00\x00\x00\x00\xF0')):
  280. return (_NAN, new_pos)
  281. # Note that we expect someone up-stack to catch struct.error and convert
  282. # it to _DecodeError -- this way we don't have to set up exception-
  283. # handling blocks every time we parse one value.
  284. result = local_unpack('<d', double_bytes)[0]
  285. return (result, new_pos)
  286. return _SimpleDecoder(wire_format.WIRETYPE_FIXED64, InnerDecode)
  287. def EnumDecoder(field_number, is_repeated, is_packed, key, new_default):
  288. enum_type = key.enum_type
  289. if is_packed:
  290. local_DecodeVarint = _DecodeVarint
  291. def DecodePackedField(buffer, pos, end, message, field_dict):
  292. value = field_dict.get(key)
  293. if value is None:
  294. value = field_dict.setdefault(key, new_default(message))
  295. (endpoint, pos) = local_DecodeVarint(buffer, pos)
  296. endpoint += pos
  297. if endpoint > end:
  298. raise _DecodeError('Truncated message.')
  299. while pos < endpoint:
  300. value_start_pos = pos
  301. (element, pos) = _DecodeSignedVarint32(buffer, pos)
  302. if element in enum_type.values_by_number:
  303. value.append(element)
  304. else:
  305. if not message._unknown_fields:
  306. message._unknown_fields = []
  307. tag_bytes = encoder.TagBytes(field_number,
  308. wire_format.WIRETYPE_VARINT)
  309. message._unknown_fields.append(
  310. (tag_bytes, buffer[value_start_pos:pos]))
  311. if pos > endpoint:
  312. if element in enum_type.values_by_number:
  313. del value[-1] # Discard corrupt value.
  314. else:
  315. del message._unknown_fields[-1]
  316. raise _DecodeError('Packed element was truncated.')
  317. return pos
  318. return DecodePackedField
  319. elif is_repeated:
  320. tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_VARINT)
  321. tag_len = len(tag_bytes)
  322. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  323. value = field_dict.get(key)
  324. if value is None:
  325. value = field_dict.setdefault(key, new_default(message))
  326. while 1:
  327. (element, new_pos) = _DecodeSignedVarint32(buffer, pos)
  328. if element in enum_type.values_by_number:
  329. value.append(element)
  330. else:
  331. if not message._unknown_fields:
  332. message._unknown_fields = []
  333. message._unknown_fields.append(
  334. (tag_bytes, buffer[pos:new_pos]))
  335. # Predict that the next tag is another copy of the same repeated
  336. # field.
  337. pos = new_pos + tag_len
  338. if buffer[new_pos:pos] != tag_bytes or new_pos >= end:
  339. # Prediction failed. Return.
  340. if new_pos > end:
  341. raise _DecodeError('Truncated message.')
  342. return new_pos
  343. return DecodeRepeatedField
  344. else:
  345. def DecodeField(buffer, pos, end, message, field_dict):
  346. value_start_pos = pos
  347. (enum_value, pos) = _DecodeSignedVarint32(buffer, pos)
  348. if pos > end:
  349. raise _DecodeError('Truncated message.')
  350. if enum_value in enum_type.values_by_number:
  351. field_dict[key] = enum_value
  352. else:
  353. if not message._unknown_fields:
  354. message._unknown_fields = []
  355. tag_bytes = encoder.TagBytes(field_number,
  356. wire_format.WIRETYPE_VARINT)
  357. message._unknown_fields.append(
  358. (tag_bytes, buffer[value_start_pos:pos]))
  359. return pos
  360. return DecodeField
  361. # --------------------------------------------------------------------
  362. Int32Decoder = _SimpleDecoder(
  363. wire_format.WIRETYPE_VARINT, _DecodeSignedVarint32)
  364. Int64Decoder = _SimpleDecoder(
  365. wire_format.WIRETYPE_VARINT, _DecodeSignedVarint)
  366. UInt32Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint32)
  367. UInt64Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint)
  368. SInt32Decoder = _ModifiedDecoder(
  369. wire_format.WIRETYPE_VARINT, _DecodeVarint32, wire_format.ZigZagDecode)
  370. SInt64Decoder = _ModifiedDecoder(
  371. wire_format.WIRETYPE_VARINT, _DecodeVarint, wire_format.ZigZagDecode)
  372. # Note that Python conveniently guarantees that when using the '<' prefix on
  373. # formats, they will also have the same size across all platforms (as opposed
  374. # to without the prefix, where their sizes depend on the C compiler's basic
  375. # type sizes).
  376. Fixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, '<I')
  377. Fixed64Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED64, '<Q')
  378. SFixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, '<i')
  379. SFixed64Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED64, '<q')
  380. FloatDecoder = _FloatDecoder()
  381. DoubleDecoder = _DoubleDecoder()
  382. BoolDecoder = _ModifiedDecoder(
  383. wire_format.WIRETYPE_VARINT, _DecodeVarint, bool)
  384. def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
  385. """Returns a decoder for a string field."""
  386. local_DecodeVarint = _DecodeVarint
  387. local_unicode = six.text_type
  388. def _ConvertToUnicode(byte_str):
  389. try:
  390. return local_unicode(byte_str, 'utf-8')
  391. except UnicodeDecodeError as e:
  392. # add more information to the error message and re-raise it.
  393. e.reason = '%s in field: %s' % (e, key.full_name)
  394. raise
  395. assert not is_packed
  396. if is_repeated:
  397. tag_bytes = encoder.TagBytes(field_number,
  398. wire_format.WIRETYPE_LENGTH_DELIMITED)
  399. tag_len = len(tag_bytes)
  400. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  401. value = field_dict.get(key)
  402. if value is None:
  403. value = field_dict.setdefault(key, new_default(message))
  404. while 1:
  405. (size, pos) = local_DecodeVarint(buffer, pos)
  406. new_pos = pos + size
  407. if new_pos > end:
  408. raise _DecodeError('Truncated string.')
  409. value.append(_ConvertToUnicode(buffer[pos:new_pos]))
  410. # Predict that the next tag is another copy of the same repeated field.
  411. pos = new_pos + tag_len
  412. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  413. # Prediction failed. Return.
  414. return new_pos
  415. return DecodeRepeatedField
  416. else:
  417. def DecodeField(buffer, pos, end, message, field_dict):
  418. (size, pos) = local_DecodeVarint(buffer, pos)
  419. new_pos = pos + size
  420. if new_pos > end:
  421. raise _DecodeError('Truncated string.')
  422. field_dict[key] = _ConvertToUnicode(buffer[pos:new_pos])
  423. return new_pos
  424. return DecodeField
  425. def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):
  426. """Returns a decoder for a bytes field."""
  427. local_DecodeVarint = _DecodeVarint
  428. assert not is_packed
  429. if is_repeated:
  430. tag_bytes = encoder.TagBytes(field_number,
  431. wire_format.WIRETYPE_LENGTH_DELIMITED)
  432. tag_len = len(tag_bytes)
  433. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  434. value = field_dict.get(key)
  435. if value is None:
  436. value = field_dict.setdefault(key, new_default(message))
  437. while 1:
  438. (size, pos) = local_DecodeVarint(buffer, pos)
  439. new_pos = pos + size
  440. if new_pos > end:
  441. raise _DecodeError('Truncated string.')
  442. value.append(buffer[pos:new_pos])
  443. # Predict that the next tag is another copy of the same repeated field.
  444. pos = new_pos + tag_len
  445. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  446. # Prediction failed. Return.
  447. return new_pos
  448. return DecodeRepeatedField
  449. else:
  450. def DecodeField(buffer, pos, end, message, field_dict):
  451. (size, pos) = local_DecodeVarint(buffer, pos)
  452. new_pos = pos + size
  453. if new_pos > end:
  454. raise _DecodeError('Truncated string.')
  455. field_dict[key] = buffer[pos:new_pos]
  456. return new_pos
  457. return DecodeField
  458. def GroupDecoder(field_number, is_repeated, is_packed, key, new_default):
  459. """Returns a decoder for a group field."""
  460. end_tag_bytes = encoder.TagBytes(field_number,
  461. wire_format.WIRETYPE_END_GROUP)
  462. end_tag_len = len(end_tag_bytes)
  463. assert not is_packed
  464. if is_repeated:
  465. tag_bytes = encoder.TagBytes(field_number,
  466. wire_format.WIRETYPE_START_GROUP)
  467. tag_len = len(tag_bytes)
  468. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  469. value = field_dict.get(key)
  470. if value is None:
  471. value = field_dict.setdefault(key, new_default(message))
  472. while 1:
  473. value = field_dict.get(key)
  474. if value is None:
  475. value = field_dict.setdefault(key, new_default(message))
  476. # Read sub-message.
  477. pos = value.add()._InternalParse(buffer, pos, end)
  478. # Read end tag.
  479. new_pos = pos+end_tag_len
  480. if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:
  481. raise _DecodeError('Missing group end tag.')
  482. # Predict that the next tag is another copy of the same repeated field.
  483. pos = new_pos + tag_len
  484. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  485. # Prediction failed. Return.
  486. return new_pos
  487. return DecodeRepeatedField
  488. else:
  489. def DecodeField(buffer, pos, end, message, field_dict):
  490. value = field_dict.get(key)
  491. if value is None:
  492. value = field_dict.setdefault(key, new_default(message))
  493. # Read sub-message.
  494. pos = value._InternalParse(buffer, pos, end)
  495. # Read end tag.
  496. new_pos = pos+end_tag_len
  497. if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:
  498. raise _DecodeError('Missing group end tag.')
  499. return new_pos
  500. return DecodeField
  501. def MessageDecoder(field_number, is_repeated, is_packed, key, new_default):
  502. """Returns a decoder for a message field."""
  503. local_DecodeVarint = _DecodeVarint
  504. assert not is_packed
  505. if is_repeated:
  506. tag_bytes = encoder.TagBytes(field_number,
  507. wire_format.WIRETYPE_LENGTH_DELIMITED)
  508. tag_len = len(tag_bytes)
  509. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  510. value = field_dict.get(key)
  511. if value is None:
  512. value = field_dict.setdefault(key, new_default(message))
  513. while 1:
  514. # Read length.
  515. (size, pos) = local_DecodeVarint(buffer, pos)
  516. new_pos = pos + size
  517. if new_pos > end:
  518. raise _DecodeError('Truncated message.')
  519. # Read sub-message.
  520. if value.add()._InternalParse(buffer, pos, new_pos) != new_pos:
  521. # The only reason _InternalParse would return early is if it
  522. # encountered an end-group tag.
  523. raise _DecodeError('Unexpected end-group tag.')
  524. # Predict that the next tag is another copy of the same repeated field.
  525. pos = new_pos + tag_len
  526. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  527. # Prediction failed. Return.
  528. return new_pos
  529. return DecodeRepeatedField
  530. else:
  531. def DecodeField(buffer, pos, end, message, field_dict):
  532. value = field_dict.get(key)
  533. if value is None:
  534. value = field_dict.setdefault(key, new_default(message))
  535. # Read length.
  536. (size, pos) = local_DecodeVarint(buffer, pos)
  537. new_pos = pos + size
  538. if new_pos > end:
  539. raise _DecodeError('Truncated message.')
  540. # Read sub-message.
  541. if value._InternalParse(buffer, pos, new_pos) != new_pos:
  542. # The only reason _InternalParse would return early is if it encountered
  543. # an end-group tag.
  544. raise _DecodeError('Unexpected end-group tag.')
  545. return new_pos
  546. return DecodeField
  547. # --------------------------------------------------------------------
  548. MESSAGE_SET_ITEM_TAG = encoder.TagBytes(1, wire_format.WIRETYPE_START_GROUP)
  549. def MessageSetItemDecoder(descriptor):
  550. """Returns a decoder for a MessageSet item.
  551. The parameter is the message Descriptor.
  552. The message set message looks like this:
  553. message MessageSet {
  554. repeated group Item = 1 {
  555. required int32 type_id = 2;
  556. required string message = 3;
  557. }
  558. }
  559. """
  560. type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT)
  561. message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)
  562. item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP)
  563. local_ReadTag = ReadTag
  564. local_DecodeVarint = _DecodeVarint
  565. local_SkipField = SkipField
  566. def DecodeItem(buffer, pos, end, message, field_dict):
  567. message_set_item_start = pos
  568. type_id = -1
  569. message_start = -1
  570. message_end = -1
  571. # Technically, type_id and message can appear in any order, so we need
  572. # a little loop here.
  573. while 1:
  574. (tag_bytes, pos) = local_ReadTag(buffer, pos)
  575. if tag_bytes == type_id_tag_bytes:
  576. (type_id, pos) = local_DecodeVarint(buffer, pos)
  577. elif tag_bytes == message_tag_bytes:
  578. (size, message_start) = local_DecodeVarint(buffer, pos)
  579. pos = message_end = message_start + size
  580. elif tag_bytes == item_end_tag_bytes:
  581. break
  582. else:
  583. pos = SkipField(buffer, pos, end, tag_bytes)
  584. if pos == -1:
  585. raise _DecodeError('Missing group end tag.')
  586. if pos > end:
  587. raise _DecodeError('Truncated message.')
  588. if type_id == -1:
  589. raise _DecodeError('MessageSet item missing type_id.')
  590. if message_start == -1:
  591. raise _DecodeError('MessageSet item missing message.')
  592. extension = message.Extensions._FindExtensionByNumber(type_id)
  593. if extension is not None:
  594. value = field_dict.get(extension)
  595. if value is None:
  596. value = field_dict.setdefault(
  597. extension, extension.message_type._concrete_class())
  598. if value._InternalParse(buffer, message_start,message_end) != message_end:
  599. # The only reason _InternalParse would return early is if it encountered
  600. # an end-group tag.
  601. raise _DecodeError('Unexpected end-group tag.')
  602. else:
  603. if not message._unknown_fields:
  604. message._unknown_fields = []
  605. message._unknown_fields.append((MESSAGE_SET_ITEM_TAG,
  606. buffer[message_set_item_start:pos]))
  607. return pos
  608. return DecodeItem
  609. # --------------------------------------------------------------------
  610. def MapDecoder(field_descriptor, new_default, is_message_map):
  611. """Returns a decoder for a map field."""
  612. key = field_descriptor
  613. tag_bytes = encoder.TagBytes(field_descriptor.number,
  614. wire_format.WIRETYPE_LENGTH_DELIMITED)
  615. tag_len = len(tag_bytes)
  616. local_DecodeVarint = _DecodeVarint
  617. # Can't read _concrete_class yet; might not be initialized.
  618. message_type = field_descriptor.message_type
  619. def DecodeMap(buffer, pos, end, message, field_dict):
  620. submsg = message_type._concrete_class()
  621. value = field_dict.get(key)
  622. if value is None:
  623. value = field_dict.setdefault(key, new_default(message))
  624. while 1:
  625. # Read length.
  626. (size, pos) = local_DecodeVarint(buffer, pos)
  627. new_pos = pos + size
  628. if new_pos > end:
  629. raise _DecodeError('Truncated message.')
  630. # Read sub-message.
  631. submsg.Clear()
  632. if submsg._InternalParse(buffer, pos, new_pos) != new_pos:
  633. # The only reason _InternalParse would return early is if it
  634. # encountered an end-group tag.
  635. raise _DecodeError('Unexpected end-group tag.')
  636. if is_message_map:
  637. value[submsg.key].MergeFrom(submsg.value)
  638. else:
  639. value[submsg.key] = submsg.value
  640. # Predict that the next tag is another copy of the same repeated field.
  641. pos = new_pos + tag_len
  642. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  643. # Prediction failed. Return.
  644. return new_pos
  645. return DecodeMap
  646. # --------------------------------------------------------------------
  647. # Optimization is not as heavy here because calls to SkipField() are rare,
  648. # except for handling end-group tags.
  649. def _SkipVarint(buffer, pos, end):
  650. """Skip a varint value. Returns the new position."""
  651. # Previously ord(buffer[pos]) raised IndexError when pos is out of range.
  652. # With this code, ord(b'') raises TypeError. Both are handled in
  653. # python_message.py to generate a 'Truncated message' error.
  654. while ord(buffer[pos:pos+1]) & 0x80:
  655. pos += 1
  656. pos += 1
  657. if pos > end:
  658. raise _DecodeError('Truncated message.')
  659. return pos
  660. def _SkipFixed64(buffer, pos, end):
  661. """Skip a fixed64 value. Returns the new position."""
  662. pos += 8
  663. if pos > end:
  664. raise _DecodeError('Truncated message.')
  665. return pos
  666. def _SkipLengthDelimited(buffer, pos, end):
  667. """Skip a length-delimited value. Returns the new position."""
  668. (size, pos) = _DecodeVarint(buffer, pos)
  669. pos += size
  670. if pos > end:
  671. raise _DecodeError('Truncated message.')
  672. return pos
  673. def _SkipGroup(buffer, pos, end):
  674. """Skip sub-group. Returns the new position."""
  675. while 1:
  676. (tag_bytes, pos) = ReadTag(buffer, pos)
  677. new_pos = SkipField(buffer, pos, end, tag_bytes)
  678. if new_pos == -1:
  679. return pos
  680. pos = new_pos
  681. def _EndGroup(buffer, pos, end):
  682. """Skipping an END_GROUP tag returns -1 to tell the parent loop to break."""
  683. return -1
  684. def _SkipFixed32(buffer, pos, end):
  685. """Skip a fixed32 value. Returns the new position."""
  686. pos += 4
  687. if pos > end:
  688. raise _DecodeError('Truncated message.')
  689. return pos
  690. def _RaiseInvalidWireType(buffer, pos, end):
  691. """Skip function for unknown wire types. Raises an exception."""
  692. raise _DecodeError('Tag had invalid wire type.')
  693. def _FieldSkipper():
  694. """Constructs the SkipField function."""
  695. WIRETYPE_TO_SKIPPER = [
  696. _SkipVarint,
  697. _SkipFixed64,
  698. _SkipLengthDelimited,
  699. _SkipGroup,
  700. _EndGroup,
  701. _SkipFixed32,
  702. _RaiseInvalidWireType,
  703. _RaiseInvalidWireType,
  704. ]
  705. wiretype_mask = wire_format.TAG_TYPE_MASK
  706. def SkipField(buffer, pos, end, tag_bytes):
  707. """Skips a field with the specified tag.
  708. |pos| should point to the byte immediately after the tag.
  709. Returns:
  710. The new position (after the tag value), or -1 if the tag is an end-group
  711. tag (in which case the calling loop should break).
  712. """
  713. # The wire type is always in the first byte since varints are little-endian.
  714. wire_type = ord(tag_bytes[0:1]) & wiretype_mask
  715. return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)
  716. return SkipField
  717. SkipField = _FieldSkipper()