1#!/usr/bin/env python
2"""Small helper class to provide a small slice of a stream."""
3
4from apitools.base.py import exceptions
5
6
7class StreamSlice(object):
8
9    """Provides a slice-like object for streams."""
10
11    def __init__(self, stream, max_bytes):
12        self.__stream = stream
13        self.__remaining_bytes = max_bytes
14        self.__max_bytes = max_bytes
15
16    def __str__(self):
17        return 'Slice of stream %s with %s/%s bytes not yet read' % (
18            self.__stream, self.__remaining_bytes, self.__max_bytes)
19
20    def __len__(self):
21        return self.__max_bytes
22
23    def __nonzero__(self):
24        # For 32-bit python2.x, len() cannot exceed a 32-bit number; avoid
25        # accidental len() calls from httplib in the form of "if this_object:".
26        return bool(self.__max_bytes)
27
28    @property
29    def length(self):
30        # For 32-bit python2.x, len() cannot exceed a 32-bit number.
31        return self.__max_bytes
32
33    def read(self, size=None):  # pylint: disable=missing-docstring
34        """Read at most size bytes from this slice.
35
36        Compared to other streams, there is one case where we may
37        unexpectedly raise an exception on read: if the underlying stream
38        is exhausted (i.e. returns no bytes on read), and the size of this
39        slice indicates we should still be able to read more bytes, we
40        raise exceptions.StreamExhausted.
41
42        Args:
43          size: If provided, read no more than size bytes from the stream.
44
45        Returns:
46          The bytes read from this slice.
47
48        Raises:
49          exceptions.StreamExhausted
50
51        """
52        if size is not None:
53            read_size = min(size, self.__remaining_bytes)
54        else:
55            read_size = self.__remaining_bytes
56        data = self.__stream.read(read_size)
57        if read_size > 0 and not data:
58            raise exceptions.StreamExhausted(
59                'Not enough bytes in stream; expected %d, exhausted '
60                'after %d' % (
61                    self.__max_bytes,
62                    self.__max_bytes - self.__remaining_bytes))
63        self.__remaining_bytes -= len(data)
64        return data
65