view src/goodjava/io/BufferedInputStream.java @ 1480:1f41e5921090

input buffering
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 24 Apr 2020 14:32:20 -0600
parents bd13aaeaf6d4
children 97740900c820
line wrap: on
line source

/*
 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package goodjava.io;

import java.io.InputStream;
import java.io.FilterInputStream;
import java.io.IOException;

/**
 * A <code>BufferedInputStream</code> adds
 * functionality to another input stream-namely,
 * the ability to buffer the input. When  the <code>BufferedInputStream</code>
 * is created, an internal buffer array is
 * created. As bytes  from the stream are read
 * or skipped, the internal buffer is refilled
 * as necessary  from the contained input stream,
 * many bytes at a time.
 *
 * @author  Arthur van Hoff
 * @since   JDK1.0
 */
public final class BufferedInputStream extends FilterInputStream {
	private static int DEFAULT_BUFFER_SIZE = 8192;
	private final byte buf[];
	private boolean isClosed = false;

	/**
	 * The index one greater than the index of the last valid byte in
	 * the buffer.
	 * This value is always
	 * in the range <code>0</code> through <code>buf.length</code>;
	 * elements <code>buf[0]</code>  through <code>buf[count-1]
	 * </code>contain buffered input data obtained
	 * from the underlying input stream.
	 */
	private int count;

	/**
	 * The current position in the buffer. This is the index of the next
	 * character to be read from the <code>buf</code> array.
	 * <p>
	 * This value is always in the range <code>0</code>
	 * through <code>count</code>. If it is less
	 * than <code>count</code>, then  <code>buf[pos]</code>
	 * is the next byte to be supplied as input;
	 * if it is equal to <code>count</code>, then
	 * the  next <code>read</code> or <code>skip</code>
	 * operation will require more bytes to be
	 * read from the contained  input stream.
	 *
	 * @see     java.io.BufferedInputStream#buf
	 */
	private int pos;

	private void checkClosed() throws IOException {
		if (isClosed)
			throw new IOException("Stream closed");
	}

	/**
	 * Creates a <code>BufferedInputStream</code>
	 * and saves its  argument, the input stream
	 * <code>in</code>, for later use. An internal
	 * buffer array is created and  stored in <code>buf</code>.
	 *
	 * @param   in   the underlying input stream.
	 */
	public BufferedInputStream(InputStream in) {
		this(in, DEFAULT_BUFFER_SIZE);
	}

	/**
	 * Creates a <code>BufferedInputStream</code>
	 * with the specified buffer size,
	 * and saves its  argument, the input stream
	 * <code>in</code>, for later use.  An internal
	 * buffer array of length  <code>size</code>
	 * is created and stored in <code>buf</code>.
	 *
	 * @param   in     the underlying input stream.
	 * @param   size   the buffer size.
	 */
	public BufferedInputStream(InputStream in, int size) {
		super(in);
		buf = new byte[size];
	}

	/**
	 * Fills the buffer with more data.
	 * Assumes that it is being called by a synchronized method.
	 * This method also assumes that all data has already been read in,
	 * hence pos > count.
	 */
	private void fill() throws IOException {
		pos = 0;
		count = 0;
		int n = super.read(buf, 0, buf.length);
		if (n > 0)
			count = n;
	}

	/**
	 * See
	 * the general contract of the <code>read</code>
	 * method of <code>InputStream</code>.
	 *
	 * @return     the next byte of data, or <code>-1</code> if the end of the
	 *             stream is reached.
	 * @exception  IOException  if this input stream has been closed by
	 *                          invoking its {@link #close()} method,
	 *                          or an I/O error occurs.
	 * @see        java.io.FilterInputStream#in
	 */
	public synchronized int read() throws IOException {
		checkClosed();
		if (pos >= count) {
			fill();
			if (pos >= count)
				return -1;
		}
		return buf[pos++] & 0xff;
	}

	/**
	 * Read characters into a portion of an array, reading from the underlying
	 * stream at most once if necessary.
	 */
	public synchronized int read(byte[] b, int off, int len) throws IOException {
		checkClosed();
		int avail = count - pos;
		if (avail <= 0) {
			/* If the requested length is at least as large as the buffer, do not bother to copy the
			   bytes into the local buffer.  In this way buffered streams will
			   cascade harmlessly. */
			if (len >= buf.length) {
				return super.read(b, off, len);
			}
			fill();
			avail = count - pos;
			if (avail <= 0) return -1;
		}
		int cnt = (avail < len) ? avail : len;
		System.arraycopy(buf, pos, b, off, cnt);
		pos += cnt;
		return cnt;
	}

	/**
	 * See the general contract of the <code>skip</code>
	 * method of <code>InputStream</code>.
	 *
	 * @exception  IOException  if the stream does not support seek,
	 *                          or if this input stream has been closed by
	 *                          invoking its {@link #close()} method, or an
	 *                          I/O error occurs.
	 */
	public synchronized long skip(long n) throws IOException {
		checkClosed();
		long avail = count - pos;
		if (avail <= 0) {
			return super.skip(n);
		}
		long skipped = (avail < n) ? avail : n;
		pos += skipped;
		return skipped;
	}

	/**
	 * Returns an estimate of the number of bytes that can be read (or
	 * skipped over) from this input stream without blocking by the next
	 * invocation of a method for this input stream. The next invocation might be
	 * the same thread or another thread.  A single read or skip of this
	 * many bytes will not block, but may read or skip fewer bytes.
	 * <p>
	 * This method returns the sum of the number of bytes remaining to be read in
	 * the buffer (<code>count&nbsp;- pos</code>) and the result of calling the
	 * {@link java.io.FilterInputStream#in in}.available().
	 *
	 * @return     an estimate of the number of bytes that can be read (or skipped
	 *             over) from this input stream without blocking.
	 * @exception  IOException  if this input stream has been closed by
	 *                          invoking its {@link #close()} method,
	 *                          or an I/O error occurs.
	 */
	public synchronized int available() throws IOException {
		int n = count - pos;
		int avail = super.available();
		return n > (Integer.MAX_VALUE - avail)
					? Integer.MAX_VALUE
					: n + avail;
	}

	public void mark(int readlimit) {}

	public void reset() throws IOException {
		throw new IOException("mark/reset not supported");
	}

	public boolean markSupported() {
		return false;
	}

	/**
	 * Closes this input stream and releases any system resources
	 * associated with the stream.
	 * Once the stream has been closed, further read(), available(), reset(),
	 * or skip() invocations will throw an IOException.
	 * Closing a previously closed stream has no effect.
	 *
	 * @exception  IOException  if an I/O error occurs.
	 */
	public synchronized void close() throws IOException {
		isClosed = true;
		super.close();
	}
}