If given content_length is an int > 0, wrap the stream
        in a LimitReader. Otherwise, return the stream unaltered
481514
def wrap_stream(stream, content_length):
        
        try:
            content_length = int(content_length)
            if content_length >= 0:
                # optimize: if already a LimitStream, set limit to
                # the smaller of the two limits
                if isinstance(stream, LimitReader):
                    stream.limit = min(stream.limit, content_length)
                else:
                    stream = LimitReader(stream, content_length)

        except (ValueError, TypeError):
            pass

        return stream
1247179
private int readFromStream(final int length) throws IOException {
        int total = 0;
        int actual = 0;
        while (total < length && actual != -1) {

            final int localIndex = getLocalWriterIndex();
            final int spaceLeft = getAvailableLocalWritingSpace();
            final int readAtMost = Math.min(length - total, spaceLeft);

            final java.nio.ByteBuffer bb = getWritingRow();

            actual = this.is.read(bb.array(), localIndex, readAtMost);

            if (actual > 0) {
                this.upperBoundary += actual;
                this.writerIndex = this.upperBoundary;
                total += actual;
            }
        }
        return total;
    }
1044356
def read(length = nil, buffer = nil)
      raise ArgumentError, "negative length #{length} given" if length && length < 0

      return '' if length == 0
      res = buffer.nil? ? '' : buffer.clear

      chunk_size = length.nil? ? @connection.buffer_size : length
      begin
        while chunk_size > 0
          chunk = readpartial(chunk_size)
          break unless chunk
          res << chunk
          chunk_size = length - res.length unless length.nil?
        end
      rescue EOFError
      end
      return length && res.length == 0 ? nil : res
    end
895360
public int getContentLength() {
        try {
            getInputStream();
        } catch (Exception e) {
            return -1;
        }
        int l = contentLength;
        if (l < 0) {
            try {
                l = Integer.parseInt(properties.findValue("content-length"));
                setContentLength(l);
            } catch(Exception e) {
            }
        }
        return l;
    }
312976
def default_stream_factory(
    total_content_length, filename, content_type, content_length=None
):
    """"""
    max_size = 1024 * 500
    if SpooledTemporaryFile is not None:
        return SpooledTemporaryFile(max_size=max_size, mode="wb+")
    if total_content_length is None or total_content_length > max_size:
        return TemporaryFile("wb+")
    return BytesIO()
972180
def readView(self, newLength=None):
        
        if newLength is None:
            newLength = self.len
        result = self.peekView(newLength)
        self.skip(newLength)
        return result
620288
private int readChunkLength()
    throws IOException
  {
    int length = 0;
    int ch;

    ReadStream is = _next;

    // skip whitespace
    for (ch = is.read();
         ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
         ch = is.read()) {
    }

    // XXX: This doesn't properly handle the case when when the browser
    // sends headers at the end of the data.  See the HTTP/1.1 spec.
    for (; ch > 0 && ch != '\r' && ch != '\n'; ch = is.read()) {
      if ('0' <= ch && ch <= '9')
        length = 16 * length + ch - '0';
      else if ('a' <= ch && ch <= 'f')
        length = 16 * length + ch - 'a' + 10;
      else if ('A' <= ch && ch <= 'F')
        length = 16 * length + ch - 'A' + 10;
      else if (ch == ' ' || ch == '\t') {
        //if (dbg.canWrite())
        //  dbg.println("unexpected chunk whitespace.");
      }
      else {
        StringBuilder sb = new StringBuilder();

        sb.append((char) ch);
        for (int ch1 = is.read();
             ch1 >= 0 && ch1 != '\r' && ch1 != '\n';
             ch1 = is.read()) {
          sb.append((char) ch1);
        }

        throw new IOException("HTTP/1.1 protocol error: bad chunk at"
                              + " '" + sb + "'"
                              + " 0x" + Integer.toHexString(ch)
                              + " length=" + length);
      }
    }

    if (ch == '\r')
      ch = is.read();

    return length;
  }
142690
private long countBySkipping(InputStream in) throws IOException {
    long count = 0;
    while (true) {
      // don't try to skip more than available()
      // things may work really wrong with FileInputStream otherwise
      long skipped = in.skip(Math.min(in.available(), Integer.MAX_VALUE));
      if (skipped <= 0) {
        if (in.read() == -1) {
          return count;
        } else if (count == 0 && in.available() == 0) {
          // if available is still zero after reading a single byte, it
          // will probably always be zero, so we should countByReading
          throw new IOException();
        }
        count++;
      } else {
        count += skipped;
      }
    }
  }
1304705
def calculate_content_length(self):
        """"""
        try:
            self._ensure_sequence()
        except RuntimeError:
            return None
        return sum(len(x) for x in self.response)
1009807
public long getContentLength(MIMETypedStream stream) {
        long length = 0;
        if (stream.header != null) {
            for (int i = 0; i < stream.header.length; i++) {
                if (stream.header[i].name != null
                        && !stream.header[i].name.equalsIgnoreCase("")
                        && stream.header[i].name.equalsIgnoreCase("content-length")) {
                    length = Long.parseLong(stream.header[i].value);
                    break;
                }
            }
        }
        return length;
    }
767086
def batch_stream(buff, stream, size=DEFAULT_BATCH_SIZE):
    
    buff.truncate(0)
    for _ in xrange(size):
        if hasattr(stream, 'readline'):
            line = stream.readline()
        else:
            try:
                line = next(stream)
            except StopIteration:
                line = ''

        # No more lines, return the tmp
        if line == '':
            buff.seek(0)
            return True
        buff.write(line)
    buff.seek(0)
    return False
102925
def read(self, size=-1):
        """"""
        if size == 0:
            return b''
        elif size < 0:
            from_buf = self._read_from_buffer()
            self._current_pos = self._content_length
            return from_buf + self._raw_reader.read()

        #
        # Return unused data first
        #
        if len(self._buffer) >= size:
            return self._read_from_buffer(size)

        #
        # If the stream is finished, return what we have.
        #
        if self._eof:
            return self._read_from_buffer()

        #
        # Fill our buffer to the required size.
        #
        # logger.debug('filling %r byte-long buffer up to %r bytes', len(self._buffer), size)
        self._fill_buffer(size)
        return self._read_from_buffer(size)
658002
async def readline(self, container = None, size = None):
        
        ret = []
        retsize = 0
        if self.eof:
            raise EOFError
        if self.errored:
            raise IOError('Stream is broken before EOF')
        while size is None or retsize < size:
            if self.pos >= len(self.data):
                await self.prepareRead(container)
            if size is None or size - retsize >= len(self.data) - self.pos:
                t = self.data[self.pos:]
                if self.isunicode:
                    p = t.find(u'\n')
                else:
                    p = t.find(b'\n')
                if p >= 0:
                    t = t[0: p + 1]
                    ret.append(t)
                    retsize += len(t)
                    self.pos += len(t)
                    break
                else:
                    ret.append(t)
                    retsize += len(t)
                    self.pos += len(t)
                    if self.dataeof:
                        self.eof = True
                        break
                    if self.dataerror:
                        self.errored = True
                        break
            else:
                t = self.data[self.pos:self.pos + (size - retsize)]
                if self.isunicode:
                    p = t.find(u'\n')
                else:
                    p = t.find(b'\n')
                if p >= 0:
                    t = t[0: p + 1]
                ret.append(t)
                self.pos += len(t)
                retsize += len(t)
                break
        if self.isunicode:
            return u''.join(ret)
        else:
            return b''.join(ret)
        if self.errored:
            raise IOError('Stream is broken before EOF')
873127
def read(self, n):
    
    while len(self.buf) < n:
      chunk = self.f.recv(4096)
      if not chunk:
        raise EndOfStreamError()
      self.buf += chunk
    res, self.buf = self.buf[:n], self.buf[n:]
    return res
1019859
public Reader<T> limit(final long limit) {
        this.limit = limit;

        if (this.pageSize == null) {
            this.pageSize = (new Long(this.limit)).intValue();
        }

        return this;
    }
1367139
public int find(int offset, int limit, byte value) {
        byte[] bytes = this.content;
        int end = limit > 0 ? limit : count;
        for (int i = offset; i < end; i++) {
            if (bytes[i] == value) return i;
        }
        return -1;
    }
962106
public int readFrom(InputStream stream) throws IOException {
        int bytesRead = stream.read(buffer);
        if (bytesRead < 0) {
            bytesInBuffer = 0;
        } else {
            bytesInBuffer = bytesRead;
        }
        return bytesRead;
    }