decoder.py 31 KB

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