encoder.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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 encoding protocol message primitives.
  31. Contains the logic for encoding every logical protocol field type
  32. into one of the 5 physical wire types.
  33. This code is designed to push the Python interpreter's performance to the
  34. limits.
  35. The basic idea is that at startup time, for every field (i.e. every
  36. FieldDescriptor) we construct two functions: a "sizer" and an "encoder". The
  37. sizer takes a value of this field's type and computes its byte size. The
  38. encoder takes a writer function and a value. It encodes the value into byte
  39. strings and invokes the writer function to write those strings. Typically the
  40. writer function is the write() method of a BytesIO.
  41. We try to do as much work as possible when constructing the writer and the
  42. sizer rather than when calling them. In particular:
  43. * We copy any needed global functions to local variables, so that we do not need
  44. to do costly global table lookups at runtime.
  45. * Similarly, we try to do any attribute lookups at startup time if possible.
  46. * Every field's tag is encoded to bytes at startup, since it can't change at
  47. runtime.
  48. * Whatever component of the field size we can compute at startup, we do.
  49. * We *avoid* sharing code if doing so would make the code slower and not sharing
  50. does not burden us too much. For example, encoders for repeated fields do
  51. not just call the encoders for singular fields in a loop because this would
  52. add an extra function call overhead for every loop iteration; instead, we
  53. manually inline the single-value encoder into the loop.
  54. * If a Python function lacks a return statement, Python actually generates
  55. instructions to pop the result of the last statement off the stack, push
  56. None onto the stack, and then return that. If we really don't care what
  57. value is returned, then we can save two instructions by returning the
  58. result of the last statement. It looks funny but it helps.
  59. * We assume that type and bounds checking has happened at a higher level.
  60. """
  61. __author__ = 'kenton@google.com (Kenton Varda)'
  62. import struct
  63. import six
  64. from google.protobuf.internal import wire_format
  65. # This will overflow and thus become IEEE-754 "infinity". We would use
  66. # "float('inf')" but it doesn't work on Windows pre-Python-2.6.
  67. _POS_INF = 1e10000
  68. _NEG_INF = -_POS_INF
  69. def _VarintSize(value):
  70. """Compute the size of a varint value."""
  71. if value <= 0x7f: return 1
  72. if value <= 0x3fff: return 2
  73. if value <= 0x1fffff: return 3
  74. if value <= 0xfffffff: return 4
  75. if value <= 0x7ffffffff: return 5
  76. if value <= 0x3ffffffffff: return 6
  77. if value <= 0x1ffffffffffff: return 7
  78. if value <= 0xffffffffffffff: return 8
  79. if value <= 0x7fffffffffffffff: return 9
  80. return 10
  81. def _SignedVarintSize(value):
  82. """Compute the size of a signed varint value."""
  83. if value < 0: return 10
  84. if value <= 0x7f: return 1
  85. if value <= 0x3fff: return 2
  86. if value <= 0x1fffff: return 3
  87. if value <= 0xfffffff: return 4
  88. if value <= 0x7ffffffff: return 5
  89. if value <= 0x3ffffffffff: return 6
  90. if value <= 0x1ffffffffffff: return 7
  91. if value <= 0xffffffffffffff: return 8
  92. if value <= 0x7fffffffffffffff: return 9
  93. return 10
  94. def _TagSize(field_number):
  95. """Returns the number of bytes required to serialize a tag with this field
  96. number."""
  97. # Just pass in type 0, since the type won't affect the tag+type size.
  98. return _VarintSize(wire_format.PackTag(field_number, 0))
  99. # --------------------------------------------------------------------
  100. # In this section we define some generic sizers. Each of these functions
  101. # takes parameters specific to a particular field type, e.g. int32 or fixed64.
  102. # It returns another function which in turn takes parameters specific to a
  103. # particular field, e.g. the field number and whether it is repeated or packed.
  104. # Look at the next section to see how these are used.
  105. def _SimpleSizer(compute_value_size):
  106. """A sizer which uses the function compute_value_size to compute the size of
  107. each value. Typically compute_value_size is _VarintSize."""
  108. def SpecificSizer(field_number, is_repeated, is_packed):
  109. tag_size = _TagSize(field_number)
  110. if is_packed:
  111. local_VarintSize = _VarintSize
  112. def PackedFieldSize(value):
  113. result = 0
  114. for element in value:
  115. result += compute_value_size(element)
  116. return result + local_VarintSize(result) + tag_size
  117. return PackedFieldSize
  118. elif is_repeated:
  119. def RepeatedFieldSize(value):
  120. result = tag_size * len(value)
  121. for element in value:
  122. result += compute_value_size(element)
  123. return result
  124. return RepeatedFieldSize
  125. else:
  126. def FieldSize(value):
  127. return tag_size + compute_value_size(value)
  128. return FieldSize
  129. return SpecificSizer
  130. def _ModifiedSizer(compute_value_size, modify_value):
  131. """Like SimpleSizer, but modify_value is invoked on each value before it is
  132. passed to compute_value_size. modify_value is typically ZigZagEncode."""
  133. def SpecificSizer(field_number, is_repeated, is_packed):
  134. tag_size = _TagSize(field_number)
  135. if is_packed:
  136. local_VarintSize = _VarintSize
  137. def PackedFieldSize(value):
  138. result = 0
  139. for element in value:
  140. result += compute_value_size(modify_value(element))
  141. return result + local_VarintSize(result) + tag_size
  142. return PackedFieldSize
  143. elif is_repeated:
  144. def RepeatedFieldSize(value):
  145. result = tag_size * len(value)
  146. for element in value:
  147. result += compute_value_size(modify_value(element))
  148. return result
  149. return RepeatedFieldSize
  150. else:
  151. def FieldSize(value):
  152. return tag_size + compute_value_size(modify_value(value))
  153. return FieldSize
  154. return SpecificSizer
  155. def _FixedSizer(value_size):
  156. """Like _SimpleSizer except for a fixed-size field. The input is the size
  157. of one value."""
  158. def SpecificSizer(field_number, is_repeated, is_packed):
  159. tag_size = _TagSize(field_number)
  160. if is_packed:
  161. local_VarintSize = _VarintSize
  162. def PackedFieldSize(value):
  163. result = len(value) * value_size
  164. return result + local_VarintSize(result) + tag_size
  165. return PackedFieldSize
  166. elif is_repeated:
  167. element_size = value_size + tag_size
  168. def RepeatedFieldSize(value):
  169. return len(value) * element_size
  170. return RepeatedFieldSize
  171. else:
  172. field_size = value_size + tag_size
  173. def FieldSize(value):
  174. return field_size
  175. return FieldSize
  176. return SpecificSizer
  177. # ====================================================================
  178. # Here we declare a sizer constructor for each field type. Each "sizer
  179. # constructor" is a function that takes (field_number, is_repeated, is_packed)
  180. # as parameters and returns a sizer, which in turn takes a field value as
  181. # a parameter and returns its encoded size.
  182. Int32Sizer = Int64Sizer = EnumSizer = _SimpleSizer(_SignedVarintSize)
  183. UInt32Sizer = UInt64Sizer = _SimpleSizer(_VarintSize)
  184. SInt32Sizer = SInt64Sizer = _ModifiedSizer(
  185. _SignedVarintSize, wire_format.ZigZagEncode)
  186. Fixed32Sizer = SFixed32Sizer = FloatSizer = _FixedSizer(4)
  187. Fixed64Sizer = SFixed64Sizer = DoubleSizer = _FixedSizer(8)
  188. BoolSizer = _FixedSizer(1)
  189. def StringSizer(field_number, is_repeated, is_packed):
  190. """Returns a sizer for a string field."""
  191. tag_size = _TagSize(field_number)
  192. local_VarintSize = _VarintSize
  193. local_len = len
  194. assert not is_packed
  195. if is_repeated:
  196. def RepeatedFieldSize(value):
  197. result = tag_size * len(value)
  198. for element in value:
  199. l = local_len(element.encode('utf-8'))
  200. result += local_VarintSize(l) + l
  201. return result
  202. return RepeatedFieldSize
  203. else:
  204. def FieldSize(value):
  205. l = local_len(value.encode('utf-8'))
  206. return tag_size + local_VarintSize(l) + l
  207. return FieldSize
  208. def BytesSizer(field_number, is_repeated, is_packed):
  209. """Returns a sizer for a bytes field."""
  210. tag_size = _TagSize(field_number)
  211. local_VarintSize = _VarintSize
  212. local_len = len
  213. assert not is_packed
  214. if is_repeated:
  215. def RepeatedFieldSize(value):
  216. result = tag_size * len(value)
  217. for element in value:
  218. l = local_len(element)
  219. result += local_VarintSize(l) + l
  220. return result
  221. return RepeatedFieldSize
  222. else:
  223. def FieldSize(value):
  224. l = local_len(value)
  225. return tag_size + local_VarintSize(l) + l
  226. return FieldSize
  227. def GroupSizer(field_number, is_repeated, is_packed):
  228. """Returns a sizer for a group field."""
  229. tag_size = _TagSize(field_number) * 2
  230. assert not is_packed
  231. if is_repeated:
  232. def RepeatedFieldSize(value):
  233. result = tag_size * len(value)
  234. for element in value:
  235. result += element.ByteSize()
  236. return result
  237. return RepeatedFieldSize
  238. else:
  239. def FieldSize(value):
  240. return tag_size + value.ByteSize()
  241. return FieldSize
  242. def MessageSizer(field_number, is_repeated, is_packed):
  243. """Returns a sizer for a message field."""
  244. tag_size = _TagSize(field_number)
  245. local_VarintSize = _VarintSize
  246. assert not is_packed
  247. if is_repeated:
  248. def RepeatedFieldSize(value):
  249. result = tag_size * len(value)
  250. for element in value:
  251. l = element.ByteSize()
  252. result += local_VarintSize(l) + l
  253. return result
  254. return RepeatedFieldSize
  255. else:
  256. def FieldSize(value):
  257. l = value.ByteSize()
  258. return tag_size + local_VarintSize(l) + l
  259. return FieldSize
  260. # --------------------------------------------------------------------
  261. # MessageSet is special: it needs custom logic to compute its size properly.
  262. def MessageSetItemSizer(field_number):
  263. """Returns a sizer for extensions of MessageSet.
  264. The message set message looks like this:
  265. message MessageSet {
  266. repeated group Item = 1 {
  267. required int32 type_id = 2;
  268. required string message = 3;
  269. }
  270. }
  271. """
  272. static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) +
  273. _TagSize(3))
  274. local_VarintSize = _VarintSize
  275. def FieldSize(value):
  276. l = value.ByteSize()
  277. return static_size + local_VarintSize(l) + l
  278. return FieldSize
  279. # --------------------------------------------------------------------
  280. # Map is special: it needs custom logic to compute its size properly.
  281. def MapSizer(field_descriptor, is_message_map):
  282. """Returns a sizer for a map field."""
  283. # Can't look at field_descriptor.message_type._concrete_class because it may
  284. # not have been initialized yet.
  285. message_type = field_descriptor.message_type
  286. message_sizer = MessageSizer(field_descriptor.number, False, False)
  287. def FieldSize(map_value):
  288. total = 0
  289. for key in map_value:
  290. value = map_value[key]
  291. # It's wasteful to create the messages and throw them away one second
  292. # later since we'll do the same for the actual encode. But there's not an
  293. # obvious way to avoid this within the current design without tons of code
  294. # duplication. For message map, value.ByteSize() should be called to
  295. # update the status.
  296. entry_msg = message_type._concrete_class(key=key, value=value)
  297. total += message_sizer(entry_msg)
  298. if is_message_map:
  299. value.ByteSize()
  300. return total
  301. return FieldSize
  302. # ====================================================================
  303. # Encoders!
  304. def _VarintEncoder():
  305. """Return an encoder for a basic varint value (does not include tag)."""
  306. def EncodeVarint(write, value):
  307. bits = value & 0x7f
  308. value >>= 7
  309. while value:
  310. write(six.int2byte(0x80|bits))
  311. bits = value & 0x7f
  312. value >>= 7
  313. return write(six.int2byte(bits))
  314. return EncodeVarint
  315. def _SignedVarintEncoder():
  316. """Return an encoder for a basic signed varint value (does not include
  317. tag)."""
  318. def EncodeSignedVarint(write, value):
  319. if value < 0:
  320. value += (1 << 64)
  321. bits = value & 0x7f
  322. value >>= 7
  323. while value:
  324. write(six.int2byte(0x80|bits))
  325. bits = value & 0x7f
  326. value >>= 7
  327. return write(six.int2byte(bits))
  328. return EncodeSignedVarint
  329. _EncodeVarint = _VarintEncoder()
  330. _EncodeSignedVarint = _SignedVarintEncoder()
  331. def _VarintBytes(value):
  332. """Encode the given integer as a varint and return the bytes. This is only
  333. called at startup time so it doesn't need to be fast."""
  334. pieces = []
  335. _EncodeVarint(pieces.append, value)
  336. return b"".join(pieces)
  337. def TagBytes(field_number, wire_type):
  338. """Encode the given tag and return the bytes. Only called at startup."""
  339. return _VarintBytes(wire_format.PackTag(field_number, wire_type))
  340. # --------------------------------------------------------------------
  341. # As with sizers (see above), we have a number of common encoder
  342. # implementations.
  343. def _SimpleEncoder(wire_type, encode_value, compute_value_size):
  344. """Return a constructor for an encoder for fields of a particular type.
  345. Args:
  346. wire_type: The field's wire type, for encoding tags.
  347. encode_value: A function which encodes an individual value, e.g.
  348. _EncodeVarint().
  349. compute_value_size: A function which computes the size of an individual
  350. value, e.g. _VarintSize().
  351. """
  352. def SpecificEncoder(field_number, is_repeated, is_packed):
  353. if is_packed:
  354. tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  355. local_EncodeVarint = _EncodeVarint
  356. def EncodePackedField(write, value):
  357. write(tag_bytes)
  358. size = 0
  359. for element in value:
  360. size += compute_value_size(element)
  361. local_EncodeVarint(write, size)
  362. for element in value:
  363. encode_value(write, element)
  364. return EncodePackedField
  365. elif is_repeated:
  366. tag_bytes = TagBytes(field_number, wire_type)
  367. def EncodeRepeatedField(write, value):
  368. for element in value:
  369. write(tag_bytes)
  370. encode_value(write, element)
  371. return EncodeRepeatedField
  372. else:
  373. tag_bytes = TagBytes(field_number, wire_type)
  374. def EncodeField(write, value):
  375. write(tag_bytes)
  376. return encode_value(write, value)
  377. return EncodeField
  378. return SpecificEncoder
  379. def _ModifiedEncoder(wire_type, encode_value, compute_value_size, modify_value):
  380. """Like SimpleEncoder but additionally invokes modify_value on every value
  381. before passing it to encode_value. Usually modify_value is ZigZagEncode."""
  382. def SpecificEncoder(field_number, is_repeated, is_packed):
  383. if is_packed:
  384. tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  385. local_EncodeVarint = _EncodeVarint
  386. def EncodePackedField(write, value):
  387. write(tag_bytes)
  388. size = 0
  389. for element in value:
  390. size += compute_value_size(modify_value(element))
  391. local_EncodeVarint(write, size)
  392. for element in value:
  393. encode_value(write, modify_value(element))
  394. return EncodePackedField
  395. elif is_repeated:
  396. tag_bytes = TagBytes(field_number, wire_type)
  397. def EncodeRepeatedField(write, value):
  398. for element in value:
  399. write(tag_bytes)
  400. encode_value(write, modify_value(element))
  401. return EncodeRepeatedField
  402. else:
  403. tag_bytes = TagBytes(field_number, wire_type)
  404. def EncodeField(write, value):
  405. write(tag_bytes)
  406. return encode_value(write, modify_value(value))
  407. return EncodeField
  408. return SpecificEncoder
  409. def _StructPackEncoder(wire_type, format):
  410. """Return a constructor for an encoder for a fixed-width field.
  411. Args:
  412. wire_type: The field's wire type, for encoding tags.
  413. format: The format string to pass to struct.pack().
  414. """
  415. value_size = struct.calcsize(format)
  416. def SpecificEncoder(field_number, is_repeated, is_packed):
  417. local_struct_pack = struct.pack
  418. if is_packed:
  419. tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  420. local_EncodeVarint = _EncodeVarint
  421. def EncodePackedField(write, value):
  422. write(tag_bytes)
  423. local_EncodeVarint(write, len(value) * value_size)
  424. for element in value:
  425. write(local_struct_pack(format, element))
  426. return EncodePackedField
  427. elif is_repeated:
  428. tag_bytes = TagBytes(field_number, wire_type)
  429. def EncodeRepeatedField(write, value):
  430. for element in value:
  431. write(tag_bytes)
  432. write(local_struct_pack(format, element))
  433. return EncodeRepeatedField
  434. else:
  435. tag_bytes = TagBytes(field_number, wire_type)
  436. def EncodeField(write, value):
  437. write(tag_bytes)
  438. return write(local_struct_pack(format, value))
  439. return EncodeField
  440. return SpecificEncoder
  441. def _FloatingPointEncoder(wire_type, format):
  442. """Return a constructor for an encoder for float fields.
  443. This is like StructPackEncoder, but catches errors that may be due to
  444. passing non-finite floating-point values to struct.pack, and makes a
  445. second attempt to encode those values.
  446. Args:
  447. wire_type: The field's wire type, for encoding tags.
  448. format: The format string to pass to struct.pack().
  449. """
  450. value_size = struct.calcsize(format)
  451. if value_size == 4:
  452. def EncodeNonFiniteOrRaise(write, value):
  453. # Remember that the serialized form uses little-endian byte order.
  454. if value == _POS_INF:
  455. write(b'\x00\x00\x80\x7F')
  456. elif value == _NEG_INF:
  457. write(b'\x00\x00\x80\xFF')
  458. elif value != value: # NaN
  459. write(b'\x00\x00\xC0\x7F')
  460. else:
  461. raise
  462. elif value_size == 8:
  463. def EncodeNonFiniteOrRaise(write, value):
  464. if value == _POS_INF:
  465. write(b'\x00\x00\x00\x00\x00\x00\xF0\x7F')
  466. elif value == _NEG_INF:
  467. write(b'\x00\x00\x00\x00\x00\x00\xF0\xFF')
  468. elif value != value: # NaN
  469. write(b'\x00\x00\x00\x00\x00\x00\xF8\x7F')
  470. else:
  471. raise
  472. else:
  473. raise ValueError('Can\'t encode floating-point values that are '
  474. '%d bytes long (only 4 or 8)' % value_size)
  475. def SpecificEncoder(field_number, is_repeated, is_packed):
  476. local_struct_pack = struct.pack
  477. if is_packed:
  478. tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  479. local_EncodeVarint = _EncodeVarint
  480. def EncodePackedField(write, value):
  481. write(tag_bytes)
  482. local_EncodeVarint(write, len(value) * value_size)
  483. for element in value:
  484. # This try/except block is going to be faster than any code that
  485. # we could write to check whether element is finite.
  486. try:
  487. write(local_struct_pack(format, element))
  488. except SystemError:
  489. EncodeNonFiniteOrRaise(write, element)
  490. return EncodePackedField
  491. elif is_repeated:
  492. tag_bytes = TagBytes(field_number, wire_type)
  493. def EncodeRepeatedField(write, value):
  494. for element in value:
  495. write(tag_bytes)
  496. try:
  497. write(local_struct_pack(format, element))
  498. except SystemError:
  499. EncodeNonFiniteOrRaise(write, element)
  500. return EncodeRepeatedField
  501. else:
  502. tag_bytes = TagBytes(field_number, wire_type)
  503. def EncodeField(write, value):
  504. write(tag_bytes)
  505. try:
  506. write(local_struct_pack(format, value))
  507. except SystemError:
  508. EncodeNonFiniteOrRaise(write, value)
  509. return EncodeField
  510. return SpecificEncoder
  511. # ====================================================================
  512. # Here we declare an encoder constructor for each field type. These work
  513. # very similarly to sizer constructors, described earlier.
  514. Int32Encoder = Int64Encoder = EnumEncoder = _SimpleEncoder(
  515. wire_format.WIRETYPE_VARINT, _EncodeSignedVarint, _SignedVarintSize)
  516. UInt32Encoder = UInt64Encoder = _SimpleEncoder(
  517. wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize)
  518. SInt32Encoder = SInt64Encoder = _ModifiedEncoder(
  519. wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize,
  520. wire_format.ZigZagEncode)
  521. # Note that Python conveniently guarantees that when using the '<' prefix on
  522. # formats, they will also have the same size across all platforms (as opposed
  523. # to without the prefix, where their sizes depend on the C compiler's basic
  524. # type sizes).
  525. Fixed32Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED32, '<I')
  526. Fixed64Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED64, '<Q')
  527. SFixed32Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED32, '<i')
  528. SFixed64Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED64, '<q')
  529. FloatEncoder = _FloatingPointEncoder(wire_format.WIRETYPE_FIXED32, '<f')
  530. DoubleEncoder = _FloatingPointEncoder(wire_format.WIRETYPE_FIXED64, '<d')
  531. def BoolEncoder(field_number, is_repeated, is_packed):
  532. """Returns an encoder for a boolean field."""
  533. false_byte = b'\x00'
  534. true_byte = b'\x01'
  535. if is_packed:
  536. tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  537. local_EncodeVarint = _EncodeVarint
  538. def EncodePackedField(write, value):
  539. write(tag_bytes)
  540. local_EncodeVarint(write, len(value))
  541. for element in value:
  542. if element:
  543. write(true_byte)
  544. else:
  545. write(false_byte)
  546. return EncodePackedField
  547. elif is_repeated:
  548. tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)
  549. def EncodeRepeatedField(write, value):
  550. for element in value:
  551. write(tag_bytes)
  552. if element:
  553. write(true_byte)
  554. else:
  555. write(false_byte)
  556. return EncodeRepeatedField
  557. else:
  558. tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)
  559. def EncodeField(write, value):
  560. write(tag_bytes)
  561. if value:
  562. return write(true_byte)
  563. return write(false_byte)
  564. return EncodeField
  565. def StringEncoder(field_number, is_repeated, is_packed):
  566. """Returns an encoder for a string field."""
  567. tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  568. local_EncodeVarint = _EncodeVarint
  569. local_len = len
  570. assert not is_packed
  571. if is_repeated:
  572. def EncodeRepeatedField(write, value):
  573. for element in value:
  574. encoded = element.encode('utf-8')
  575. write(tag)
  576. local_EncodeVarint(write, local_len(encoded))
  577. write(encoded)
  578. return EncodeRepeatedField
  579. else:
  580. def EncodeField(write, value):
  581. encoded = value.encode('utf-8')
  582. write(tag)
  583. local_EncodeVarint(write, local_len(encoded))
  584. return write(encoded)
  585. return EncodeField
  586. def BytesEncoder(field_number, is_repeated, is_packed):
  587. """Returns an encoder for a bytes field."""
  588. tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  589. local_EncodeVarint = _EncodeVarint
  590. local_len = len
  591. assert not is_packed
  592. if is_repeated:
  593. def EncodeRepeatedField(write, value):
  594. for element in value:
  595. write(tag)
  596. local_EncodeVarint(write, local_len(element))
  597. write(element)
  598. return EncodeRepeatedField
  599. else:
  600. def EncodeField(write, value):
  601. write(tag)
  602. local_EncodeVarint(write, local_len(value))
  603. return write(value)
  604. return EncodeField
  605. def GroupEncoder(field_number, is_repeated, is_packed):
  606. """Returns an encoder for a group field."""
  607. start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP)
  608. end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP)
  609. assert not is_packed
  610. if is_repeated:
  611. def EncodeRepeatedField(write, value):
  612. for element in value:
  613. write(start_tag)
  614. element._InternalSerialize(write)
  615. write(end_tag)
  616. return EncodeRepeatedField
  617. else:
  618. def EncodeField(write, value):
  619. write(start_tag)
  620. value._InternalSerialize(write)
  621. return write(end_tag)
  622. return EncodeField
  623. def MessageEncoder(field_number, is_repeated, is_packed):
  624. """Returns an encoder for a message field."""
  625. tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  626. local_EncodeVarint = _EncodeVarint
  627. assert not is_packed
  628. if is_repeated:
  629. def EncodeRepeatedField(write, value):
  630. for element in value:
  631. write(tag)
  632. local_EncodeVarint(write, element.ByteSize())
  633. element._InternalSerialize(write)
  634. return EncodeRepeatedField
  635. else:
  636. def EncodeField(write, value):
  637. write(tag)
  638. local_EncodeVarint(write, value.ByteSize())
  639. return value._InternalSerialize(write)
  640. return EncodeField
  641. # --------------------------------------------------------------------
  642. # As before, MessageSet is special.
  643. def MessageSetItemEncoder(field_number):
  644. """Encoder for extensions of MessageSet.
  645. The message set message looks like this:
  646. message MessageSet {
  647. repeated group Item = 1 {
  648. required int32 type_id = 2;
  649. required string message = 3;
  650. }
  651. }
  652. """
  653. start_bytes = b"".join([
  654. TagBytes(1, wire_format.WIRETYPE_START_GROUP),
  655. TagBytes(2, wire_format.WIRETYPE_VARINT),
  656. _VarintBytes(field_number),
  657. TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)])
  658. end_bytes = TagBytes(1, wire_format.WIRETYPE_END_GROUP)
  659. local_EncodeVarint = _EncodeVarint
  660. def EncodeField(write, value):
  661. write(start_bytes)
  662. local_EncodeVarint(write, value.ByteSize())
  663. value._InternalSerialize(write)
  664. return write(end_bytes)
  665. return EncodeField
  666. # --------------------------------------------------------------------
  667. # As before, Map is special.
  668. def MapEncoder(field_descriptor):
  669. """Encoder for extensions of MessageSet.
  670. Maps always have a wire format like this:
  671. message MapEntry {
  672. key_type key = 1;
  673. value_type value = 2;
  674. }
  675. repeated MapEntry map = N;
  676. """
  677. # Can't look at field_descriptor.message_type._concrete_class because it may
  678. # not have been initialized yet.
  679. message_type = field_descriptor.message_type
  680. encode_message = MessageEncoder(field_descriptor.number, False, False)
  681. def EncodeField(write, value):
  682. for key in value:
  683. entry_msg = message_type._concrete_class(key=key, value=value[key])
  684. encode_message(write, entry_msg)
  685. return EncodeField