1#!/usr/bin/env python
2#
3# Copyright 2015 Google Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Small helper class to provide a small slice of a stream."""
18
19from apitools.base.py import exceptions
20
21
22class StreamSlice(object):
23
24    """Provides a slice-like object for streams."""
25
26    def __init__(self, stream, max_bytes):
27        self.__stream = stream
28        self.__remaining_bytes = max_bytes
29        self.__max_bytes = max_bytes
30
31    def __str__(self):
32        return 'Slice of stream %s with %s/%s bytes not yet read' % (
33            self.__stream, self.__remaining_bytes, self.__max_bytes)
34
35    def __len__(self):
36        return self.__max_bytes
37
38    def __nonzero__(self):
39        # For 32-bit python2.x, len() cannot exceed a 32-bit number; avoid
40        # accidental len() calls from httplib in the form of "if this_object:".
41        return bool(self.__max_bytes)
42
43    @property
44    def length(self):
45        # For 32-bit python2.x, len() cannot exceed a 32-bit number.
46        return self.__max_bytes
47
48    def read(self, size=None):  # pylint: disable=missing-docstring
49        """Read at most size bytes from this slice.
50
51        Compared to other streams, there is one case where we may
52        unexpectedly raise an exception on read: if the underlying stream
53        is exhausted (i.e. returns no bytes on read), and the size of this
54        slice indicates we should still be able to read more bytes, we
55        raise exceptions.StreamExhausted.
56
57        Args:
58          size: If provided, read no more than size bytes from the stream.
59
60        Returns:
61          The bytes read from this slice.
62
63        Raises:
64          exceptions.StreamExhausted
65
66        """
67        if size is not None:
68            read_size = min(size, self.__remaining_bytes)
69        else:
70            read_size = self.__remaining_bytes
71        data = self.__stream.read(read_size)
72        if read_size > 0 and not data:
73            raise exceptions.StreamExhausted(
74                'Not enough bytes in stream; expected %d, exhausted '
75                'after %d' % (
76                    self.__max_bytes,
77                    self.__max_bytes - self.__remaining_bytes))
78        self.__remaining_bytes -= len(data)
79        return data
80