Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

720 lines
26 KiB

  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # http://code.google.com/p/protobuf/
  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__ = '[email protected] (Kenton Varda)'
  73. import struct
  74. from google.protobuf.internal import encoder
  75. from google.protobuf.internal import wire_format
  76. from google.protobuf import message
  77. # This will overflow and thus become IEEE-754 "infinity". We would use
  78. # "float('inf')" but it doesn't work on Windows pre-Python-2.6.
  79. _POS_INF = 1e10000
  80. _NEG_INF = -_POS_INF
  81. _NAN = _POS_INF * 0
  82. # This is not for optimization, but rather to avoid conflicts with local
  83. # variables named "message".
  84. _DecodeError = message.DecodeError
  85. def _VarintDecoder(mask):
  86. """Return an encoder for a basic varint value (does not include tag).
  87. Decoded values will be bitwise-anded with the given mask before being
  88. returned, e.g. to limit them to 32 bits. The returned decoder does not
  89. take the usual "end" parameter -- the caller is expected to do bounds checking
  90. after the fact (often the caller can defer such checking until later). The
  91. decoder returns a (value, new_pos) pair.
  92. """
  93. local_ord = ord
  94. def DecodeVarint(buffer, pos):
  95. result = 0
  96. shift = 0
  97. while 1:
  98. b = local_ord(buffer[pos])
  99. result |= ((b & 0x7f) << shift)
  100. pos += 1
  101. if not (b & 0x80):
  102. result &= mask
  103. return (result, pos)
  104. shift += 7
  105. if shift >= 64:
  106. raise _DecodeError('Too many bytes when decoding varint.')
  107. return DecodeVarint
  108. def _SignedVarintDecoder(mask):
  109. """Like _VarintDecoder() but decodes signed values."""
  110. local_ord = ord
  111. def DecodeVarint(buffer, pos):
  112. result = 0
  113. shift = 0
  114. while 1:
  115. b = local_ord(buffer[pos])
  116. result |= ((b & 0x7f) << shift)
  117. pos += 1
  118. if not (b & 0x80):
  119. if result > 0x7fffffffffffffff:
  120. result -= (1 << 64)
  121. result |= ~mask
  122. else:
  123. result &= mask
  124. return (result, pos)
  125. shift += 7
  126. if shift >= 64:
  127. raise _DecodeError('Too many bytes when decoding varint.')
  128. return DecodeVarint
  129. _DecodeVarint = _VarintDecoder((1 << 64) - 1)
  130. _DecodeSignedVarint = _SignedVarintDecoder((1 << 64) - 1)
  131. # Use these versions for values which must be limited to 32 bits.
  132. _DecodeVarint32 = _VarintDecoder((1 << 32) - 1)
  133. _DecodeSignedVarint32 = _SignedVarintDecoder((1 << 32) - 1)
  134. def ReadTag(buffer, pos):
  135. """Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
  136. We return the raw bytes of the tag rather than decoding them. The raw
  137. bytes can then be used to look up the proper decoder. This effectively allows
  138. us to trade some work that would be done in pure-python (decoding a varint)
  139. for work that is done in C (searching for a byte string in a hash table).
  140. In a low-level language it would be much cheaper to decode the varint and
  141. use that, but not in Python.
  142. """
  143. start = pos
  144. while ord(buffer[pos]) & 0x80:
  145. pos += 1
  146. pos += 1
  147. return (buffer[start:pos], pos)
  148. # --------------------------------------------------------------------
  149. def _SimpleDecoder(wire_type, decode_value):
  150. """Return a constructor for a decoder for fields of a particular type.
  151. Args:
  152. wire_type: The field's wire type.
  153. decode_value: A function which decodes an individual value, e.g.
  154. _DecodeVarint()
  155. """
  156. def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default):
  157. if is_packed:
  158. local_DecodeVarint = _DecodeVarint
  159. def DecodePackedField(buffer, pos, end, message, field_dict):
  160. value = field_dict.get(key)
  161. if value is None:
  162. value = field_dict.setdefault(key, new_default(message))
  163. (endpoint, pos) = local_DecodeVarint(buffer, pos)
  164. endpoint += pos
  165. if endpoint > end:
  166. raise _DecodeError('Truncated message.')
  167. while pos < endpoint:
  168. (element, pos) = decode_value(buffer, pos)
  169. value.append(element)
  170. if pos > endpoint:
  171. del value[-1] # Discard corrupt value.
  172. raise _DecodeError('Packed element was truncated.')
  173. return pos
  174. return DecodePackedField
  175. elif is_repeated:
  176. tag_bytes = encoder.TagBytes(field_number, wire_type)
  177. tag_len = len(tag_bytes)
  178. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  179. value = field_dict.get(key)
  180. if value is None:
  181. value = field_dict.setdefault(key, new_default(message))
  182. while 1:
  183. (element, new_pos) = decode_value(buffer, pos)
  184. value.append(element)
  185. # Predict that the next tag is another copy of the same repeated
  186. # field.
  187. pos = new_pos + tag_len
  188. if buffer[new_pos:pos] != tag_bytes or new_pos >= end:
  189. # Prediction failed. Return.
  190. if new_pos > end:
  191. raise _DecodeError('Truncated message.')
  192. return new_pos
  193. return DecodeRepeatedField
  194. else:
  195. def DecodeField(buffer, pos, end, message, field_dict):
  196. (field_dict[key], pos) = decode_value(buffer, pos)
  197. if pos > end:
  198. del field_dict[key] # Discard corrupt value.
  199. raise _DecodeError('Truncated message.')
  200. return pos
  201. return DecodeField
  202. return SpecificDecoder
  203. def _ModifiedDecoder(wire_type, decode_value, modify_value):
  204. """Like SimpleDecoder but additionally invokes modify_value on every value
  205. before storing it. Usually modify_value is ZigZagDecode.
  206. """
  207. # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
  208. # not enough to make a significant difference.
  209. def InnerDecode(buffer, pos):
  210. (result, new_pos) = decode_value(buffer, pos)
  211. return (modify_value(result), new_pos)
  212. return _SimpleDecoder(wire_type, InnerDecode)
  213. def _StructPackDecoder(wire_type, format):
  214. """Return a constructor for a decoder for a fixed-width field.
  215. Args:
  216. wire_type: The field's wire type.
  217. format: The format string to pass to struct.unpack().
  218. """
  219. value_size = struct.calcsize(format)
  220. local_unpack = struct.unpack
  221. # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
  222. # not enough to make a significant difference.
  223. # Note that we expect someone up-stack to catch struct.error and convert
  224. # it to _DecodeError -- this way we don't have to set up exception-
  225. # handling blocks every time we parse one value.
  226. def InnerDecode(buffer, pos):
  227. new_pos = pos + value_size
  228. result = local_unpack(format, buffer[pos:new_pos])[0]
  229. return (result, new_pos)
  230. return _SimpleDecoder(wire_type, InnerDecode)
  231. def _FloatDecoder():
  232. """Returns a decoder for a float field.
  233. This code works around a bug in struct.unpack for non-finite 32-bit
  234. floating-point values.
  235. """
  236. local_unpack = struct.unpack
  237. def InnerDecode(buffer, pos):
  238. # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign
  239. # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand.
  240. new_pos = pos + 4
  241. float_bytes = buffer[pos:new_pos]
  242. # If this value has all its exponent bits set, then it's non-finite.
  243. # In Python 2.4, struct.unpack will convert it to a finite 64-bit value.
  244. # To avoid that, we parse it specially.
  245. if ((float_bytes[3] in '\x7F\xFF')
  246. and (float_bytes[2] >= '\x80')):
  247. # If at least one significand bit is set...
  248. if float_bytes[0:3] != '\x00\x00\x80':
  249. return (_NAN, new_pos)
  250. # If sign bit is set...
  251. if float_bytes[3] == '\xFF':
  252. return (_NEG_INF, new_pos)
  253. return (_POS_INF, new_pos)
  254. # Note that we expect someone up-stack to catch struct.error and convert
  255. # it to _DecodeError -- this way we don't have to set up exception-
  256. # handling blocks every time we parse one value.
  257. result = local_unpack('<f', float_bytes)[0]
  258. return (result, new_pos)
  259. return _SimpleDecoder(wire_format.WIRETYPE_FIXED32, InnerDecode)
  260. def _DoubleDecoder():
  261. """Returns a decoder for a double field.
  262. This code works around a bug in struct.unpack for not-a-number.
  263. """
  264. local_unpack = struct.unpack
  265. def InnerDecode(buffer, pos):
  266. # We expect a 64-bit value in little-endian byte order. Bit 1 is the sign
  267. # bit, bits 2-12 represent the exponent, and bits 13-64 are the significand.
  268. new_pos = pos + 8
  269. double_bytes = buffer[pos:new_pos]
  270. # If this value has all its exponent bits set and at least one significand
  271. # bit set, it's not a number. In Python 2.4, struct.unpack will treat it
  272. # as inf or -inf. To avoid that, we treat it specially.
  273. if ((double_bytes[7] in '\x7F\xFF')
  274. and (double_bytes[6] >= '\xF0')
  275. and (double_bytes[0:7] != '\x00\x00\x00\x00\x00\x00\xF0')):
  276. return (_NAN, new_pos)
  277. # Note that we expect someone up-stack to catch struct.error and convert
  278. # it to _DecodeError -- this way we don't have to set up exception-
  279. # handling blocks every time we parse one value.
  280. result = local_unpack('<d', double_bytes)[0]
  281. return (result, new_pos)
  282. return _SimpleDecoder(wire_format.WIRETYPE_FIXED64, InnerDecode)
  283. # --------------------------------------------------------------------
  284. Int32Decoder = EnumDecoder = _SimpleDecoder(
  285. wire_format.WIRETYPE_VARINT, _DecodeSignedVarint32)
  286. Int64Decoder = _SimpleDecoder(
  287. wire_format.WIRETYPE_VARINT, _DecodeSignedVarint)
  288. UInt32Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint32)
  289. UInt64Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint)
  290. SInt32Decoder = _ModifiedDecoder(
  291. wire_format.WIRETYPE_VARINT, _DecodeVarint32, wire_format.ZigZagDecode)
  292. SInt64Decoder = _ModifiedDecoder(
  293. wire_format.WIRETYPE_VARINT, _DecodeVarint, wire_format.ZigZagDecode)
  294. # Note that Python conveniently guarantees that when using the '<' prefix on
  295. # formats, they will also have the same size across all platforms (as opposed
  296. # to without the prefix, where their sizes depend on the C compiler's basic
  297. # type sizes).
  298. Fixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, '<I')
  299. Fixed64Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED64, '<Q')
  300. SFixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, '<i')
  301. SFixed64Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED64, '<q')
  302. FloatDecoder = _FloatDecoder()
  303. DoubleDecoder = _DoubleDecoder()
  304. BoolDecoder = _ModifiedDecoder(
  305. wire_format.WIRETYPE_VARINT, _DecodeVarint, bool)
  306. def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
  307. """Returns a decoder for a string field."""
  308. local_DecodeVarint = _DecodeVarint
  309. local_unicode = unicode
  310. assert not is_packed
  311. if is_repeated:
  312. tag_bytes = encoder.TagBytes(field_number,
  313. wire_format.WIRETYPE_LENGTH_DELIMITED)
  314. tag_len = len(tag_bytes)
  315. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  316. value = field_dict.get(key)
  317. if value is None:
  318. value = field_dict.setdefault(key, new_default(message))
  319. while 1:
  320. (size, pos) = local_DecodeVarint(buffer, pos)
  321. new_pos = pos + size
  322. if new_pos > end:
  323. raise _DecodeError('Truncated string.')
  324. value.append(local_unicode(buffer[pos:new_pos], 'utf-8'))
  325. # Predict that the next tag is another copy of the same repeated field.
  326. pos = new_pos + tag_len
  327. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  328. # Prediction failed. Return.
  329. return new_pos
  330. return DecodeRepeatedField
  331. else:
  332. def DecodeField(buffer, pos, end, message, field_dict):
  333. (size, pos) = local_DecodeVarint(buffer, pos)
  334. new_pos = pos + size
  335. if new_pos > end:
  336. raise _DecodeError('Truncated string.')
  337. field_dict[key] = local_unicode(buffer[pos:new_pos], 'utf-8')
  338. return new_pos
  339. return DecodeField
  340. def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):
  341. """Returns a decoder for a bytes field."""
  342. local_DecodeVarint = _DecodeVarint
  343. assert not is_packed
  344. if is_repeated:
  345. tag_bytes = encoder.TagBytes(field_number,
  346. wire_format.WIRETYPE_LENGTH_DELIMITED)
  347. tag_len = len(tag_bytes)
  348. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  349. value = field_dict.get(key)
  350. if value is None:
  351. value = field_dict.setdefault(key, new_default(message))
  352. while 1:
  353. (size, pos) = local_DecodeVarint(buffer, pos)
  354. new_pos = pos + size
  355. if new_pos > end:
  356. raise _DecodeError('Truncated string.')
  357. value.append(buffer[pos:new_pos])
  358. # Predict that the next tag is another copy of the same repeated field.
  359. pos = new_pos + tag_len
  360. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  361. # Prediction failed. Return.
  362. return new_pos
  363. return DecodeRepeatedField
  364. else:
  365. def DecodeField(buffer, pos, end, message, field_dict):
  366. (size, pos) = local_DecodeVarint(buffer, pos)
  367. new_pos = pos + size
  368. if new_pos > end:
  369. raise _DecodeError('Truncated string.')
  370. field_dict[key] = buffer[pos:new_pos]
  371. return new_pos
  372. return DecodeField
  373. def GroupDecoder(field_number, is_repeated, is_packed, key, new_default):
  374. """Returns a decoder for a group field."""
  375. end_tag_bytes = encoder.TagBytes(field_number,
  376. wire_format.WIRETYPE_END_GROUP)
  377. end_tag_len = len(end_tag_bytes)
  378. assert not is_packed
  379. if is_repeated:
  380. tag_bytes = encoder.TagBytes(field_number,
  381. wire_format.WIRETYPE_START_GROUP)
  382. tag_len = len(tag_bytes)
  383. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  384. value = field_dict.get(key)
  385. if value is None:
  386. value = field_dict.setdefault(key, new_default(message))
  387. while 1:
  388. value = field_dict.get(key)
  389. if value is None:
  390. value = field_dict.setdefault(key, new_default(message))
  391. # Read sub-message.
  392. pos = value.add()._InternalParse(buffer, pos, end)
  393. # Read end tag.
  394. new_pos = pos+end_tag_len
  395. if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:
  396. raise _DecodeError('Missing group end tag.')
  397. # Predict that the next tag is another copy of the same repeated field.
  398. pos = new_pos + tag_len
  399. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  400. # Prediction failed. Return.
  401. return new_pos
  402. return DecodeRepeatedField
  403. else:
  404. def DecodeField(buffer, pos, end, message, field_dict):
  405. value = field_dict.get(key)
  406. if value is None:
  407. value = field_dict.setdefault(key, new_default(message))
  408. # Read sub-message.
  409. pos = value._InternalParse(buffer, pos, end)
  410. # Read end tag.
  411. new_pos = pos+end_tag_len
  412. if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:
  413. raise _DecodeError('Missing group end tag.')
  414. return new_pos
  415. return DecodeField
  416. def MessageDecoder(field_number, is_repeated, is_packed, key, new_default):
  417. """Returns a decoder for a message field."""
  418. local_DecodeVarint = _DecodeVarint
  419. assert not is_packed
  420. if is_repeated:
  421. tag_bytes = encoder.TagBytes(field_number,
  422. wire_format.WIRETYPE_LENGTH_DELIMITED)
  423. tag_len = len(tag_bytes)
  424. def DecodeRepeatedField(buffer, pos, end, message, field_dict):
  425. value = field_dict.get(key)
  426. if value is None:
  427. value = field_dict.setdefault(key, new_default(message))
  428. while 1:
  429. value = field_dict.get(key)
  430. if value is None:
  431. value = field_dict.setdefault(key, new_default(message))
  432. # Read length.
  433. (size, pos) = local_DecodeVarint(buffer, pos)
  434. new_pos = pos + size
  435. if new_pos > end:
  436. raise _DecodeError('Truncated message.')
  437. # Read sub-message.
  438. if value.add()._InternalParse(buffer, pos, new_pos) != new_pos:
  439. # The only reason _InternalParse would return early is if it
  440. # encountered an end-group tag.
  441. raise _DecodeError('Unexpected end-group tag.')
  442. # Predict that the next tag is another copy of the same repeated field.
  443. pos = new_pos + tag_len
  444. if buffer[new_pos:pos] != tag_bytes or new_pos == end:
  445. # Prediction failed. Return.
  446. return new_pos
  447. return DecodeRepeatedField
  448. else:
  449. def DecodeField(buffer, pos, end, message, field_dict):
  450. value = field_dict.get(key)
  451. if value is None:
  452. value = field_dict.setdefault(key, new_default(message))
  453. # Read length.
  454. (size, pos) = local_DecodeVarint(buffer, pos)
  455. new_pos = pos + size
  456. if new_pos > end:
  457. raise _DecodeError('Truncated message.')
  458. # Read sub-message.
  459. if value._InternalParse(buffer, pos, new_pos) != new_pos:
  460. # The only reason _InternalParse would return early is if it encountered
  461. # an end-group tag.
  462. raise _DecodeError('Unexpected end-group tag.')
  463. return new_pos
  464. return DecodeField
  465. # --------------------------------------------------------------------
  466. MESSAGE_SET_ITEM_TAG = encoder.TagBytes(1, wire_format.WIRETYPE_START_GROUP)
  467. def MessageSetItemDecoder(extensions_by_number):
  468. """Returns a decoder for a MessageSet item.
  469. The parameter is the _extensions_by_number map for the message class.
  470. The message set message looks like this:
  471. message MessageSet {
  472. repeated group Item = 1 {
  473. required int32 type_id = 2;
  474. required string message = 3;
  475. }
  476. }
  477. """
  478. type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT)
  479. message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)
  480. item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP)
  481. local_ReadTag = ReadTag
  482. local_DecodeVarint = _DecodeVarint
  483. local_SkipField = SkipField
  484. def DecodeItem(buffer, pos, end, message, field_dict):
  485. message_set_item_start = pos
  486. type_id = -1
  487. message_start = -1
  488. message_end = -1
  489. # Technically, type_id and message can appear in any order, so we need
  490. # a little loop here.
  491. while 1:
  492. (tag_bytes, pos) = local_ReadTag(buffer, pos)
  493. if tag_bytes == type_id_tag_bytes:
  494. (type_id, pos) = local_DecodeVarint(buffer, pos)
  495. elif tag_bytes == message_tag_bytes:
  496. (size, message_start) = local_DecodeVarint(buffer, pos)
  497. pos = message_end = message_start + size
  498. elif tag_bytes == item_end_tag_bytes:
  499. break
  500. else:
  501. pos = SkipField(buffer, pos, end, tag_bytes)
  502. if pos == -1:
  503. raise _DecodeError('Missing group end tag.')
  504. if pos > end:
  505. raise _DecodeError('Truncated message.')
  506. if type_id == -1:
  507. raise _DecodeError('MessageSet item missing type_id.')
  508. if message_start == -1:
  509. raise _DecodeError('MessageSet item missing message.')
  510. extension = extensions_by_number.get(type_id)
  511. if extension is not None:
  512. value = field_dict.get(extension)
  513. if value is None:
  514. value = field_dict.setdefault(
  515. extension, extension.message_type._concrete_class())
  516. if value._InternalParse(buffer, message_start,message_end) != message_end:
  517. # The only reason _InternalParse would return early is if it encountered
  518. # an end-group tag.
  519. raise _DecodeError('Unexpected end-group tag.')
  520. else:
  521. if not message._unknown_fields:
  522. message._unknown_fields = []
  523. message._unknown_fields.append((MESSAGE_SET_ITEM_TAG,
  524. buffer[message_set_item_start:pos]))
  525. return pos
  526. return DecodeItem
  527. # --------------------------------------------------------------------
  528. # Optimization is not as heavy here because calls to SkipField() are rare,
  529. # except for handling end-group tags.
  530. def _SkipVarint(buffer, pos, end):
  531. """Skip a varint value. Returns the new position."""
  532. while ord(buffer[pos]) & 0x80:
  533. pos += 1
  534. pos += 1
  535. if pos > end:
  536. raise _DecodeError('Truncated message.')
  537. return pos
  538. def _SkipFixed64(buffer, pos, end):
  539. """Skip a fixed64 value. Returns the new position."""
  540. pos += 8
  541. if pos > end:
  542. raise _DecodeError('Truncated message.')
  543. return pos
  544. def _SkipLengthDelimited(buffer, pos, end):
  545. """Skip a length-delimited value. Returns the new position."""
  546. (size, pos) = _DecodeVarint(buffer, pos)
  547. pos += size
  548. if pos > end:
  549. raise _DecodeError('Truncated message.')
  550. return pos
  551. def _SkipGroup(buffer, pos, end):
  552. """Skip sub-group. Returns the new position."""
  553. while 1:
  554. (tag_bytes, pos) = ReadTag(buffer, pos)
  555. new_pos = SkipField(buffer, pos, end, tag_bytes)
  556. if new_pos == -1:
  557. return pos
  558. pos = new_pos
  559. def _EndGroup(buffer, pos, end):
  560. """Skipping an END_GROUP tag returns -1 to tell the parent loop to break."""
  561. return -1
  562. def _SkipFixed32(buffer, pos, end):
  563. """Skip a fixed32 value. Returns the new position."""
  564. pos += 4
  565. if pos > end:
  566. raise _DecodeError('Truncated message.')
  567. return pos
  568. def _RaiseInvalidWireType(buffer, pos, end):
  569. """Skip function for unknown wire types. Raises an exception."""
  570. raise _DecodeError('Tag had invalid wire type.')
  571. def _FieldSkipper():
  572. """Constructs the SkipField function."""
  573. WIRETYPE_TO_SKIPPER = [
  574. _SkipVarint,
  575. _SkipFixed64,
  576. _SkipLengthDelimited,
  577. _SkipGroup,
  578. _EndGroup,
  579. _SkipFixed32,
  580. _RaiseInvalidWireType,
  581. _RaiseInvalidWireType,
  582. ]
  583. wiretype_mask = wire_format.TAG_TYPE_MASK
  584. local_ord = ord
  585. def SkipField(buffer, pos, end, tag_bytes):
  586. """Skips a field with the specified tag.
  587. |pos| should point to the byte immediately after the tag.
  588. Returns:
  589. The new position (after the tag value), or -1 if the tag is an end-group
  590. tag (in which case the calling loop should break).
  591. """
  592. # The wire type is always in the first byte since varints are little-endian.
  593. wire_type = local_ord(tag_bytes[0]) & wiretype_mask
  594. return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)
  595. return SkipField
  596. SkipField = _FieldSkipper()