input_stream.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. """InputStream is the primitive interface for reading bits from the wire.
  31. All protocol buffer deserialization can be expressed in terms of
  32. the InputStream primitives provided here.
  33. """
  34. __author__ = 'robinson@google.com (Will Robinson)'
  35. import array
  36. import struct
  37. from google.protobuf import message
  38. from google.protobuf.internal import wire_format
  39. # Note that much of this code is ported from //net/proto/ProtocolBuffer, and
  40. # that the interface is strongly inspired by CodedInputStream from the C++
  41. # proto2 implementation.
  42. class InputStreamBuffer(object):
  43. """Contains all logic for reading bits, and dealing with stream position.
  44. If an InputStream method ever raises an exception, the stream is left
  45. in an indeterminate state and is not safe for further use.
  46. """
  47. def __init__(self, s):
  48. # What we really want is something like array('B', s), where elements we
  49. # read from the array are already given to us as one-byte integers. BUT
  50. # using array() instead of buffer() would force full string copies to result
  51. # from each GetSubBuffer() call.
  52. #
  53. # So, if the N serialized bytes of a single protocol buffer object are
  54. # split evenly between 2 child messages, and so on recursively, using
  55. # array('B', s) instead of buffer() would incur an additional N*logN bytes
  56. # copied during deserialization.
  57. #
  58. # The higher constant overhead of having to ord() for every byte we read
  59. # from the buffer in _ReadVarintHelper() could definitely lead to worse
  60. # performance in many real-world scenarios, even if the asymptotic
  61. # complexity is better. However, our real answer is that the mythical
  62. # Python/C extension module output mode for the protocol compiler will
  63. # be blazing-fast and will eliminate most use of this class anyway.
  64. self._buffer = buffer(s)
  65. self._pos = 0
  66. def EndOfStream(self):
  67. """Returns true iff we're at the end of the stream.
  68. If this returns true, then a call to any other InputStream method
  69. will raise an exception.
  70. """
  71. return self._pos >= len(self._buffer)
  72. def Position(self):
  73. """Returns the current position in the stream, or equivalently, the
  74. number of bytes read so far.
  75. """
  76. return self._pos
  77. def GetSubBuffer(self, size=None):
  78. """Returns a sequence-like object that represents a portion of our
  79. underlying sequence.
  80. Position 0 in the returned object corresponds to self.Position()
  81. in this stream.
  82. If size is specified, then the returned object ends after the
  83. next "size" bytes in this stream. If size is not specified,
  84. then the returned object ends at the end of this stream.
  85. We guarantee that the returned object R supports the Python buffer
  86. interface (and thus that the call buffer(R) will work).
  87. Note that the returned buffer is read-only.
  88. The intended use for this method is for nested-message and nested-group
  89. deserialization, where we want to make a recursive MergeFromString()
  90. call on the portion of the original sequence that contains the serialized
  91. nested message. (And we'd like to do so without making unnecessary string
  92. copies).
  93. REQUIRES: size is nonnegative.
  94. """
  95. # Note that buffer() doesn't perform any actual string copy.
  96. if size is None:
  97. return buffer(self._buffer, self._pos)
  98. else:
  99. if size < 0:
  100. raise message.DecodeError('Negative size %d' % size)
  101. return buffer(self._buffer, self._pos, size)
  102. def SkipBytes(self, num_bytes):
  103. """Skip num_bytes bytes ahead, or go to the end of the stream, whichever
  104. comes first.
  105. REQUIRES: num_bytes is nonnegative.
  106. """
  107. if num_bytes < 0:
  108. raise message.DecodeError('Negative num_bytes %d' % num_bytes)
  109. self._pos += num_bytes
  110. self._pos = min(self._pos, len(self._buffer))
  111. def ReadBytes(self, size):
  112. """Reads up to 'size' bytes from the stream, stopping early
  113. only if we reach the end of the stream. Returns the bytes read
  114. as a string.
  115. """
  116. if size < 0:
  117. raise message.DecodeError('Negative size %d' % size)
  118. s = (self._buffer[self._pos : self._pos + size])
  119. self._pos += len(s) # Only advance by the number of bytes actually read.
  120. return s
  121. def ReadLittleEndian32(self):
  122. """Interprets the next 4 bytes of the stream as a little-endian
  123. encoded, unsiged 32-bit integer, and returns that integer.
  124. """
  125. try:
  126. i = struct.unpack(wire_format.FORMAT_UINT32_LITTLE_ENDIAN,
  127. self._buffer[self._pos : self._pos + 4])
  128. self._pos += 4
  129. return i[0] # unpack() result is a 1-element tuple.
  130. except struct.error, e:
  131. raise message.DecodeError(e)
  132. def ReadLittleEndian64(self):
  133. """Interprets the next 8 bytes of the stream as a little-endian
  134. encoded, unsiged 64-bit integer, and returns that integer.
  135. """
  136. try:
  137. i = struct.unpack(wire_format.FORMAT_UINT64_LITTLE_ENDIAN,
  138. self._buffer[self._pos : self._pos + 8])
  139. self._pos += 8
  140. return i[0] # unpack() result is a 1-element tuple.
  141. except struct.error, e:
  142. raise message.DecodeError(e)
  143. def ReadVarint32(self):
  144. """Reads a varint from the stream, interprets this varint
  145. as a signed, 32-bit integer, and returns the integer.
  146. """
  147. i = self.ReadVarint64()
  148. if not wire_format.INT32_MIN <= i <= wire_format.INT32_MAX:
  149. raise message.DecodeError('Value out of range for int32: %d' % i)
  150. return int(i)
  151. def ReadVarUInt32(self):
  152. """Reads a varint from the stream, interprets this varint
  153. as an unsigned, 32-bit integer, and returns the integer.
  154. """
  155. i = self.ReadVarUInt64()
  156. if i > wire_format.UINT32_MAX:
  157. raise message.DecodeError('Value out of range for uint32: %d' % i)
  158. return i
  159. def ReadVarint64(self):
  160. """Reads a varint from the stream, interprets this varint
  161. as a signed, 64-bit integer, and returns the integer.
  162. """
  163. i = self.ReadVarUInt64()
  164. if i > wire_format.INT64_MAX:
  165. i -= (1 << 64)
  166. return i
  167. def ReadVarUInt64(self):
  168. """Reads a varint from the stream, interprets this varint
  169. as an unsigned, 64-bit integer, and returns the integer.
  170. """
  171. i = self._ReadVarintHelper()
  172. if not 0 <= i <= wire_format.UINT64_MAX:
  173. raise message.DecodeError('Value out of range for uint64: %d' % i)
  174. return i
  175. def _ReadVarintHelper(self):
  176. """Helper for the various varint-reading methods above.
  177. Reads an unsigned, varint-encoded integer from the stream and
  178. returns this integer.
  179. Does no bounds checking except to ensure that we read at most as many bytes
  180. as could possibly be present in a varint-encoded 64-bit number.
  181. """
  182. result = 0
  183. shift = 0
  184. while 1:
  185. if shift >= 64:
  186. raise message.DecodeError('Too many bytes when decoding varint.')
  187. try:
  188. b = ord(self._buffer[self._pos])
  189. except IndexError:
  190. raise message.DecodeError('Truncated varint.')
  191. self._pos += 1
  192. result |= ((b & 0x7f) << shift)
  193. shift += 7
  194. if not (b & 0x80):
  195. return result
  196. class InputStreamArray(object):
  197. """Contains all logic for reading bits, and dealing with stream position.
  198. If an InputStream method ever raises an exception, the stream is left
  199. in an indeterminate state and is not safe for further use.
  200. This alternative to InputStreamBuffer is used in environments where buffer()
  201. is unavailble, such as Google App Engine.
  202. """
  203. def __init__(self, s):
  204. self._buffer = array.array('B', s)
  205. self._pos = 0
  206. def EndOfStream(self):
  207. return self._pos >= len(self._buffer)
  208. def Position(self):
  209. return self._pos
  210. def GetSubBuffer(self, size=None):
  211. if size is None:
  212. return self._buffer[self._pos : ].tostring()
  213. else:
  214. if size < 0:
  215. raise message.DecodeError('Negative size %d' % size)
  216. return self._buffer[self._pos : self._pos + size].tostring()
  217. def SkipBytes(self, num_bytes):
  218. if num_bytes < 0:
  219. raise message.DecodeError('Negative num_bytes %d' % num_bytes)
  220. self._pos += num_bytes
  221. self._pos = min(self._pos, len(self._buffer))
  222. def ReadBytes(self, size):
  223. if size < 0:
  224. raise message.DecodeError('Negative size %d' % size)
  225. s = self._buffer[self._pos : self._pos + size].tostring()
  226. self._pos += len(s) # Only advance by the number of bytes actually read.
  227. return s
  228. def ReadLittleEndian32(self):
  229. try:
  230. i = struct.unpack(wire_format.FORMAT_UINT32_LITTLE_ENDIAN,
  231. self._buffer[self._pos : self._pos + 4])
  232. self._pos += 4
  233. return i[0] # unpack() result is a 1-element tuple.
  234. except struct.error, e:
  235. raise message.DecodeError(e)
  236. def ReadLittleEndian64(self):
  237. try:
  238. i = struct.unpack(wire_format.FORMAT_UINT64_LITTLE_ENDIAN,
  239. self._buffer[self._pos : self._pos + 8])
  240. self._pos += 8
  241. return i[0] # unpack() result is a 1-element tuple.
  242. except struct.error, e:
  243. raise message.DecodeError(e)
  244. def ReadVarint32(self):
  245. i = self.ReadVarint64()
  246. if not wire_format.INT32_MIN <= i <= wire_format.INT32_MAX:
  247. raise message.DecodeError('Value out of range for int32: %d' % i)
  248. return int(i)
  249. def ReadVarUInt32(self):
  250. i = self.ReadVarUInt64()
  251. if i > wire_format.UINT32_MAX:
  252. raise message.DecodeError('Value out of range for uint32: %d' % i)
  253. return i
  254. def ReadVarint64(self):
  255. i = self.ReadVarUInt64()
  256. if i > wire_format.INT64_MAX:
  257. i -= (1 << 64)
  258. return i
  259. def ReadVarUInt64(self):
  260. i = self._ReadVarintHelper()
  261. if not 0 <= i <= wire_format.UINT64_MAX:
  262. raise message.DecodeError('Value out of range for uint64: %d' % i)
  263. return i
  264. def _ReadVarintHelper(self):
  265. result = 0
  266. shift = 0
  267. while 1:
  268. if shift >= 64:
  269. raise message.DecodeError('Too many bytes when decoding varint.')
  270. try:
  271. b = self._buffer[self._pos]
  272. except IndexError:
  273. raise message.DecodeError('Truncated varint.')
  274. self._pos += 1
  275. result |= ((b & 0x7f) << shift)
  276. shift += 7
  277. if not (b & 0x80):
  278. return result
  279. try:
  280. buffer('')
  281. InputStream = InputStreamBuffer
  282. except NotImplementedError:
  283. # Google App Engine: dev_appserver.py
  284. InputStream = InputStreamArray
  285. except RuntimeError:
  286. # Google App Engine: production
  287. InputStream = InputStreamArray