File: stream_slice.py

package info (click to toggle)
python-googlecloudapis 0.9.30%2Bdebian1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,112 kB
  • ctags: 4,163
  • sloc: python: 10,137; makefile: 28
file content (50 lines) | stat: -rwxr-xr-x 1,608 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""Small helper class to provide a small slice of a stream."""

from googlecloudapis.apitools.base.py import exceptions


class StreamSlice(object):
  """Provides a slice-like object for streams."""

  def __init__(self, stream, max_bytes):
    self.__stream = stream
    self.__remaining_bytes = max_bytes
    self.__max_bytes = max_bytes

  def __str__(self):
    return 'Slice of stream %s with %s/%s bytes not yet read' % (
        self.__stream, self.__remaining_bytes, self.__max_bytes)

  def __len__(self):
    return self.__max_bytes

  def read(self, size=None):  # pylint: disable=missing-docstring
    """Read at most size bytes from this slice.

    Compared to other streams, there is one case where we may
    unexpectedly raise an exception on read: if the underlying stream
    is exhausted (i.e. returns no bytes on read), and the size of this
    slice indicates we should still be able to read more bytes, we
    raise exceptions.StreamExhausted.

    Args:
      size: If provided, read no more than size bytes from the stream.

    Returns:
      The bytes read from this slice.

    Raises:
      exceptions.StreamExhausted

    """
    if size is not None:
      read_size = min(size, self.__remaining_bytes)
    else:
      read_size = self.__remaining_bytes
    data = self.__stream.read(read_size)
    if read_size > 0 and not data:
      raise exceptions.StreamExhausted(
          'Not enough bytes in stream; expected %d, exhausted after %d' % (
              self.__max_bytes, self.__max_bytes - self.__remaining_bytes))
    self.__remaining_bytes -= len(data)
    return data