encoder.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. """Class 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. """
  34. __author__ = 'robinson@google.com (Will Robinson)'
  35. import struct
  36. from froofle.protobuf import message
  37. from froofle.protobuf.internal import wire_format
  38. from froofle.protobuf.internal import output_stream
  39. # Note that much of this code is ported from //net/proto/ProtocolBuffer, and
  40. # that the interface is strongly inspired by WireFormat from the C++ proto2
  41. # implementation.
  42. class Encoder(object):
  43. """Encodes logical protocol buffer fields to the wire format."""
  44. def __init__(self):
  45. self._stream = output_stream.OutputStream()
  46. def ToString(self):
  47. """Returns all values encoded in this object as a string."""
  48. return self._stream.ToString()
  49. # All the Append*() methods below first append a tag+type pair to the buffer
  50. # before appending the specified value.
  51. def AppendInt32(self, field_number, value):
  52. """Appends a 32-bit integer to our buffer, varint-encoded."""
  53. self._AppendTag(field_number, wire_format.WIRETYPE_VARINT)
  54. self._stream.AppendVarint32(value)
  55. def AppendInt64(self, field_number, value):
  56. """Appends a 64-bit integer to our buffer, varint-encoded."""
  57. self._AppendTag(field_number, wire_format.WIRETYPE_VARINT)
  58. self._stream.AppendVarint64(value)
  59. def AppendUInt32(self, field_number, unsigned_value):
  60. """Appends an unsigned 32-bit integer to our buffer, varint-encoded."""
  61. self._AppendTag(field_number, wire_format.WIRETYPE_VARINT)
  62. self._stream.AppendVarUInt32(unsigned_value)
  63. def AppendUInt64(self, field_number, unsigned_value):
  64. """Appends an unsigned 64-bit integer to our buffer, varint-encoded."""
  65. self._AppendTag(field_number, wire_format.WIRETYPE_VARINT)
  66. self._stream.AppendVarUInt64(unsigned_value)
  67. def AppendSInt32(self, field_number, value):
  68. """Appends a 32-bit integer to our buffer, zigzag-encoded and then
  69. varint-encoded.
  70. """
  71. self._AppendTag(field_number, wire_format.WIRETYPE_VARINT)
  72. zigzag_value = wire_format.ZigZagEncode(value)
  73. self._stream.AppendVarUInt32(zigzag_value)
  74. def AppendSInt64(self, field_number, value):
  75. """Appends a 64-bit integer to our buffer, zigzag-encoded and then
  76. varint-encoded.
  77. """
  78. self._AppendTag(field_number, wire_format.WIRETYPE_VARINT)
  79. zigzag_value = wire_format.ZigZagEncode(value)
  80. self._stream.AppendVarUInt64(zigzag_value)
  81. def AppendFixed32(self, field_number, unsigned_value):
  82. """Appends an unsigned 32-bit integer to our buffer, in little-endian
  83. byte-order.
  84. """
  85. self._AppendTag(field_number, wire_format.WIRETYPE_FIXED32)
  86. self._stream.AppendLittleEndian32(unsigned_value)
  87. def AppendFixed64(self, field_number, unsigned_value):
  88. """Appends an unsigned 64-bit integer to our buffer, in little-endian
  89. byte-order.
  90. """
  91. self._AppendTag(field_number, wire_format.WIRETYPE_FIXED64)
  92. self._stream.AppendLittleEndian64(unsigned_value)
  93. def AppendSFixed32(self, field_number, value):
  94. """Appends a signed 32-bit integer to our buffer, in little-endian
  95. byte-order.
  96. """
  97. sign = (value & 0x80000000) and -1 or 0
  98. if value >> 32 != sign:
  99. raise message.EncodeError('SFixed32 out of range: %d' % value)
  100. self._AppendTag(field_number, wire_format.WIRETYPE_FIXED32)
  101. self._stream.AppendLittleEndian32(value & 0xffffffff)
  102. def AppendSFixed64(self, field_number, value):
  103. """Appends a signed 64-bit integer to our buffer, in little-endian
  104. byte-order.
  105. """
  106. sign = (value & 0x8000000000000000) and -1 or 0
  107. if value >> 64 != sign:
  108. raise message.EncodeError('SFixed64 out of range: %d' % value)
  109. self._AppendTag(field_number, wire_format.WIRETYPE_FIXED64)
  110. self._stream.AppendLittleEndian64(value & 0xffffffffffffffff)
  111. def AppendFloat(self, field_number, value):
  112. """Appends a floating-point number to our buffer."""
  113. self._AppendTag(field_number, wire_format.WIRETYPE_FIXED32)
  114. self._stream.AppendRawBytes(struct.pack('f', value))
  115. def AppendDouble(self, field_number, value):
  116. """Appends a double-precision floating-point number to our buffer."""
  117. self._AppendTag(field_number, wire_format.WIRETYPE_FIXED64)
  118. self._stream.AppendRawBytes(struct.pack('d', value))
  119. def AppendBool(self, field_number, value):
  120. """Appends a boolean to our buffer."""
  121. self.AppendInt32(field_number, value)
  122. def AppendEnum(self, field_number, value):
  123. """Appends an enum value to our buffer."""
  124. self.AppendInt32(field_number, value)
  125. def AppendString(self, field_number, value):
  126. """Appends a length-prefixed unicode string, encoded as UTF-8 to our buffer,
  127. with the length varint-encoded.
  128. """
  129. self.AppendBytes(field_number, value.encode('utf-8'))
  130. def AppendBytes(self, field_number, value):
  131. """Appends a length-prefixed sequence of bytes to our buffer, with the
  132. length varint-encoded.
  133. """
  134. self._AppendTag(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  135. self._stream.AppendVarUInt32(len(value))
  136. self._stream.AppendRawBytes(value)
  137. # TODO(robinson): For AppendGroup() and AppendMessage(), we'd really like to
  138. # avoid the extra string copy here. We can do so if we widen the Message
  139. # interface to be able to serialize to a stream in addition to a string. The
  140. # challenge when thinking ahead to the Python/C API implementation of Message
  141. # is finding a stream-like Python thing to which we can write raw bytes
  142. # from C. I'm not sure such a thing exists(?). (array.array is pretty much
  143. # what we want, but it's not directly exposed in the Python/C API).
  144. def AppendGroup(self, field_number, group):
  145. """Appends a group to our buffer.
  146. """
  147. self._AppendTag(field_number, wire_format.WIRETYPE_START_GROUP)
  148. self._stream.AppendRawBytes(group.SerializeToString())
  149. self._AppendTag(field_number, wire_format.WIRETYPE_END_GROUP)
  150. def AppendMessage(self, field_number, msg):
  151. """Appends a nested message to our buffer.
  152. """
  153. self._AppendTag(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  154. self._stream.AppendVarUInt32(msg.ByteSize())
  155. self._stream.AppendRawBytes(msg.SerializeToString())
  156. def AppendMessageSetItem(self, field_number, msg):
  157. """Appends an item using the message set wire format.
  158. The message set message looks like this:
  159. message MessageSet {
  160. repeated group Item = 1 {
  161. required int32 type_id = 2;
  162. required string message = 3;
  163. }
  164. }
  165. """
  166. self._AppendTag(1, wire_format.WIRETYPE_START_GROUP)
  167. self.AppendInt32(2, field_number)
  168. self.AppendMessage(3, msg)
  169. self._AppendTag(1, wire_format.WIRETYPE_END_GROUP)
  170. def _AppendTag(self, field_number, wire_type):
  171. """Appends a tag containing field number and wire type information."""
  172. self._stream.AppendVarUInt32(wire_format.PackTag(field_number, wire_type))