Home | History | Annotate | Download | only in io
      1 /*
      2  * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
      3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      4  *
      5  * This code is free software; you can redistribute it and/or modify it
      6  * under the terms of the GNU General Public License version 2 only, as
      7  * published by the Free Software Foundation.  Oracle designates this
      8  * particular file as subject to the "Classpath" exception as provided
      9  * by Oracle in the LICENSE file that accompanied this code.
     10  *
     11  * This code is distributed in the hope that it will be useful, but WITHOUT
     12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
     13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
     14  * version 2 for more details (a copy is included in the LICENSE file that
     15  * accompanied this code).
     16  *
     17  * You should have received a copy of the GNU General Public License version
     18  * 2 along with this work; if not, write to the Free Software Foundation,
     19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
     20  *
     21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
     22  * or visit www.oracle.com if you need additional information or have any
     23  * questions.
     24  */
     25 
     26 package java.io;
     27 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
     28 
     29 /**
     30  * A <code>BufferedInputStream</code> adds
     31  * functionality to another input stream-namely,
     32  * the ability to buffer the input and to
     33  * support the <code>mark</code> and <code>reset</code>
     34  * methods. When  the <code>BufferedInputStream</code>
     35  * is created, an internal buffer array is
     36  * created. As bytes  from the stream are read
     37  * or skipped, the internal buffer is refilled
     38  * as necessary  from the contained input stream,
     39  * many bytes at a time. The <code>mark</code>
     40  * operation  remembers a point in the input
     41  * stream and the <code>reset</code> operation
     42  * causes all the  bytes read since the most
     43  * recent <code>mark</code> operation to be
     44  * reread before new bytes are  taken from
     45  * the contained input stream.
     46  *
     47  * @author  Arthur van Hoff
     48  * @since   JDK1.0
     49  */
     50 public
     51 class BufferedInputStream extends FilterInputStream {
     52 
     53     // Android-changed: made final
     54     private static final int DEFAULT_BUFFER_SIZE = 8192;
     55 
     56     /**
     57      * The maximum size of array to allocate.
     58      * Some VMs reserve some header words in an array.
     59      * Attempts to allocate larger arrays may result in
     60      * OutOfMemoryError: Requested array size exceeds VM limit
     61      */
     62     // Android-changed: made final
     63     private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
     64 
     65     /**
     66      * The internal buffer array where the data is stored. When necessary,
     67      * it may be replaced by another array of
     68      * a different size.
     69      */
     70     protected volatile byte buf[];
     71 
     72     /**
     73      * Atomic updater to provide compareAndSet for buf. This is
     74      * necessary because closes can be asynchronous. We use nullness
     75      * of buf[] as primary indicator that this stream is closed. (The
     76      * "in" field is also nulled out on close.)
     77      */
     78     private static final
     79         AtomicReferenceFieldUpdater<BufferedInputStream, byte[]> bufUpdater =
     80         AtomicReferenceFieldUpdater.newUpdater
     81         (BufferedInputStream.class,  byte[].class, "buf");
     82 
     83     /**
     84      * The index one greater than the index of the last valid byte in
     85      * the buffer.
     86      * This value is always
     87      * in the range <code>0</code> through <code>buf.length</code>;
     88      * elements <code>buf[0]</code>  through <code>buf[count-1]
     89      * </code>contain buffered input data obtained
     90      * from the underlying  input stream.
     91      */
     92     protected int count;
     93 
     94     /**
     95      * The current position in the buffer. This is the index of the next
     96      * character to be read from the <code>buf</code> array.
     97      * <p>
     98      * This value is always in the range <code>0</code>
     99      * through <code>count</code>. If it is less
    100      * than <code>count</code>, then  <code>buf[pos]</code>
    101      * is the next byte to be supplied as input;
    102      * if it is equal to <code>count</code>, then
    103      * the  next <code>read</code> or <code>skip</code>
    104      * operation will require more bytes to be
    105      * read from the contained  input stream.
    106      *
    107      * @see     java.io.BufferedInputStream#buf
    108      */
    109     protected int pos;
    110 
    111     /**
    112      * The value of the <code>pos</code> field at the time the last
    113      * <code>mark</code> method was called.
    114      * <p>
    115      * This value is always
    116      * in the range <code>-1</code> through <code>pos</code>.
    117      * If there is no marked position in  the input
    118      * stream, this field is <code>-1</code>. If
    119      * there is a marked position in the input
    120      * stream,  then <code>buf[markpos]</code>
    121      * is the first byte to be supplied as input
    122      * after a <code>reset</code> operation. If
    123      * <code>markpos</code> is not <code>-1</code>,
    124      * then all bytes from positions <code>buf[markpos]</code>
    125      * through  <code>buf[pos-1]</code> must remain
    126      * in the buffer array (though they may be
    127      * moved to  another place in the buffer array,
    128      * with suitable adjustments to the values
    129      * of <code>count</code>,  <code>pos</code>,
    130      * and <code>markpos</code>); they may not
    131      * be discarded unless and until the difference
    132      * between <code>pos</code> and <code>markpos</code>
    133      * exceeds <code>marklimit</code>.
    134      *
    135      * @see     java.io.BufferedInputStream#mark(int)
    136      * @see     java.io.BufferedInputStream#pos
    137      */
    138     protected int markpos = -1;
    139 
    140     /**
    141      * The maximum read ahead allowed after a call to the
    142      * <code>mark</code> method before subsequent calls to the
    143      * <code>reset</code> method fail.
    144      * Whenever the difference between <code>pos</code>
    145      * and <code>markpos</code> exceeds <code>marklimit</code>,
    146      * then the  mark may be dropped by setting
    147      * <code>markpos</code> to <code>-1</code>.
    148      *
    149      * @see     java.io.BufferedInputStream#mark(int)
    150      * @see     java.io.BufferedInputStream#reset()
    151      */
    152     protected int marklimit;
    153 
    154     /**
    155      * Check to make sure that underlying input stream has not been
    156      * nulled out due to close; if not return it;
    157      */
    158     private InputStream getInIfOpen() throws IOException {
    159         InputStream input = in;
    160         if (input == null)
    161             throw new IOException("Stream closed");
    162         return input;
    163     }
    164 
    165     /**
    166      * Check to make sure that buffer has not been nulled out due to
    167      * close; if not return it;
    168      */
    169     private byte[] getBufIfOpen() throws IOException {
    170         byte[] buffer = buf;
    171         if (buffer == null)
    172             throw new IOException("Stream closed");
    173         return buffer;
    174     }
    175 
    176     /**
    177      * Creates a <code>BufferedInputStream</code>
    178      * and saves its  argument, the input stream
    179      * <code>in</code>, for later use. An internal
    180      * buffer array is created and  stored in <code>buf</code>.
    181      *
    182      * @param   in   the underlying input stream.
    183      */
    184     public BufferedInputStream(InputStream in) {
    185         this(in, DEFAULT_BUFFER_SIZE);
    186     }
    187 
    188     /**
    189      * Creates a <code>BufferedInputStream</code>
    190      * with the specified buffer size,
    191      * and saves its  argument, the input stream
    192      * <code>in</code>, for later use.  An internal
    193      * buffer array of length  <code>size</code>
    194      * is created and stored in <code>buf</code>.
    195      *
    196      * @param   in     the underlying input stream.
    197      * @param   size   the buffer size.
    198      * @exception IllegalArgumentException if {@code size <= 0}.
    199      */
    200     public BufferedInputStream(InputStream in, int size) {
    201         super(in);
    202         if (size <= 0) {
    203             throw new IllegalArgumentException("Buffer size <= 0");
    204         }
    205         buf = new byte[size];
    206     }
    207 
    208     /**
    209      * Fills the buffer with more data, taking into account
    210      * shuffling and other tricks for dealing with marks.
    211      * Assumes that it is being called by a synchronized method.
    212      * This method also assumes that all data has already been read in,
    213      * hence pos > count.
    214      */
    215     private void fill() throws IOException {
    216         byte[] buffer = getBufIfOpen();
    217         if (markpos < 0)
    218             pos = 0;            /* no mark: throw away the buffer */
    219         else if (pos >= buffer.length)  /* no room left in buffer */
    220             if (markpos > 0) {  /* can throw away early part of the buffer */
    221                 int sz = pos - markpos;
    222                 System.arraycopy(buffer, markpos, buffer, 0, sz);
    223                 pos = sz;
    224                 markpos = 0;
    225             } else if (buffer.length >= marklimit) {
    226                 markpos = -1;   /* buffer got too big, invalidate mark */
    227                 pos = 0;        /* drop buffer contents */
    228             } else if (buffer.length >= MAX_BUFFER_SIZE) {
    229                 throw new OutOfMemoryError("Required array size too large");
    230             } else {            /* grow buffer */
    231                 int nsz = (pos <= MAX_BUFFER_SIZE - pos) ?
    232                         pos * 2 : MAX_BUFFER_SIZE;
    233                 if (nsz > marklimit)
    234                     nsz = marklimit;
    235                 byte nbuf[] = new byte[nsz];
    236                 System.arraycopy(buffer, 0, nbuf, 0, pos);
    237                 if (!bufUpdater.compareAndSet(this, buffer, nbuf)) {
    238                     // Can't replace buf if there was an async close.
    239                     // Note: This would need to be changed if fill()
    240                     // is ever made accessible to multiple threads.
    241                     // But for now, the only way CAS can fail is via close.
    242                     // assert buf == null;
    243                     throw new IOException("Stream closed");
    244                 }
    245                 buffer = nbuf;
    246             }
    247         count = pos;
    248         int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
    249         if (n > 0)
    250             count = n + pos;
    251     }
    252 
    253     /**
    254      * See
    255      * the general contract of the <code>read</code>
    256      * method of <code>InputStream</code>.
    257      *
    258      * @return     the next byte of data, or <code>-1</code> if the end of the
    259      *             stream is reached.
    260      * @exception  IOException  if this input stream has been closed by
    261      *                          invoking its {@link #close()} method,
    262      *                          or an I/O error occurs.
    263      * @see        java.io.FilterInputStream#in
    264      */
    265     public synchronized int read() throws IOException {
    266         if (pos >= count) {
    267             fill();
    268             if (pos >= count)
    269                 return -1;
    270         }
    271         return getBufIfOpen()[pos++] & 0xff;
    272     }
    273 
    274     /**
    275      * Read characters into a portion of an array, reading from the underlying
    276      * stream at most once if necessary.
    277      */
    278     private int read1(byte[] b, int off, int len) throws IOException {
    279         int avail = count - pos;
    280         if (avail <= 0) {
    281             /* If the requested length is at least as large as the buffer, and
    282                if there is no mark/reset activity, do not bother to copy the
    283                bytes into the local buffer.  In this way buffered streams will
    284                cascade harmlessly. */
    285             if (len >= getBufIfOpen().length && markpos < 0) {
    286                 return getInIfOpen().read(b, off, len);
    287             }
    288             fill();
    289             avail = count - pos;
    290             if (avail <= 0) return -1;
    291         }
    292         int cnt = (avail < len) ? avail : len;
    293         System.arraycopy(getBufIfOpen(), pos, b, off, cnt);
    294         pos += cnt;
    295         return cnt;
    296     }
    297 
    298     /**
    299      * Reads bytes from this byte-input stream into the specified byte array,
    300      * starting at the given offset.
    301      *
    302      * <p> This method implements the general contract of the corresponding
    303      * <code>{@link InputStream#read(byte[], int, int) read}</code> method of
    304      * the <code>{@link InputStream}</code> class.  As an additional
    305      * convenience, it attempts to read as many bytes as possible by repeatedly
    306      * invoking the <code>read</code> method of the underlying stream.  This
    307      * iterated <code>read</code> continues until one of the following
    308      * conditions becomes true: <ul>
    309      *
    310      *   <li> The specified number of bytes have been read,
    311      *
    312      *   <li> The <code>read</code> method of the underlying stream returns
    313      *   <code>-1</code>, indicating end-of-file, or
    314      *
    315      *   <li> The <code>available</code> method of the underlying stream
    316      *   returns zero, indicating that further input requests would block.
    317      *
    318      * </ul> If the first <code>read</code> on the underlying stream returns
    319      * <code>-1</code> to indicate end-of-file then this method returns
    320      * <code>-1</code>.  Otherwise this method returns the number of bytes
    321      * actually read.
    322      *
    323      * <p> Subclasses of this class are encouraged, but not required, to
    324      * attempt to read as many bytes as possible in the same fashion.
    325      *
    326      * @param      b     destination buffer.
    327      * @param      off   offset at which to start storing bytes.
    328      * @param      len   maximum number of bytes to read.
    329      * @return     the number of bytes read, or <code>-1</code> if the end of
    330      *             the stream has been reached.
    331      * @exception  IOException  if this input stream has been closed by
    332      *                          invoking its {@link #close()} method,
    333      *                          or an I/O error occurs.
    334      */
    335     public synchronized int read(byte b[], int off, int len)
    336         throws IOException
    337     {
    338         getBufIfOpen(); // Check for closed stream
    339         if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
    340             throw new IndexOutOfBoundsException();
    341         } else if (len == 0) {
    342             return 0;
    343         }
    344 
    345         int n = 0;
    346         for (;;) {
    347             int nread = read1(b, off + n, len - n);
    348             if (nread <= 0)
    349                 return (n == 0) ? nread : n;
    350             n += nread;
    351             if (n >= len)
    352                 return n;
    353             // if not closed but no bytes available, return
    354             InputStream input = in;
    355             if (input != null && input.available() <= 0)
    356                 return n;
    357         }
    358     }
    359 
    360     /**
    361      * See the general contract of the <code>skip</code>
    362      * method of <code>InputStream</code>.
    363      *
    364      * @exception  IOException  if the stream does not support seek,
    365      *                          or if this input stream has been closed by
    366      *                          invoking its {@link #close()} method, or an
    367      *                          I/O error occurs.
    368      */
    369     public synchronized long skip(long n) throws IOException {
    370         getBufIfOpen(); // Check for closed stream
    371         if (n <= 0) {
    372             return 0;
    373         }
    374         long avail = count - pos;
    375 
    376         if (avail <= 0) {
    377             // If no mark position set then don't keep in buffer
    378             if (markpos <0)
    379                 return getInIfOpen().skip(n);
    380 
    381             // Fill in buffer to save bytes for reset
    382             fill();
    383             avail = count - pos;
    384             if (avail <= 0)
    385                 return 0;
    386         }
    387 
    388         long skipped = (avail < n) ? avail : n;
    389         pos += skipped;
    390         return skipped;
    391     }
    392 
    393     /**
    394      * Returns an estimate of the number of bytes that can be read (or
    395      * skipped over) from this input stream without blocking by the next
    396      * invocation of a method for this input stream. The next invocation might be
    397      * the same thread or another thread.  A single read or skip of this
    398      * many bytes will not block, but may read or skip fewer bytes.
    399      * <p>
    400      * This method returns the sum of the number of bytes remaining to be read in
    401      * the buffer (<code>count&nbsp;- pos</code>) and the result of calling the
    402      * {@link java.io.FilterInputStream#in in}.available().
    403      *
    404      * @return     an estimate of the number of bytes that can be read (or skipped
    405      *             over) from this input stream without blocking.
    406      * @exception  IOException  if this input stream has been closed by
    407      *                          invoking its {@link #close()} method,
    408      *                          or an I/O error occurs.
    409      */
    410     public synchronized int available() throws IOException {
    411         int n = count - pos;
    412         int avail = getInIfOpen().available();
    413         return n > (Integer.MAX_VALUE - avail)
    414                     ? Integer.MAX_VALUE
    415                     : n + avail;
    416     }
    417 
    418     /**
    419      * See the general contract of the <code>mark</code>
    420      * method of <code>InputStream</code>.
    421      *
    422      * @param   readlimit   the maximum limit of bytes that can be read before
    423      *                      the mark position becomes invalid.
    424      * @see     java.io.BufferedInputStream#reset()
    425      */
    426     public synchronized void mark(int readlimit) {
    427         marklimit = readlimit;
    428         markpos = pos;
    429     }
    430 
    431     /**
    432      * See the general contract of the <code>reset</code>
    433      * method of <code>InputStream</code>.
    434      * <p>
    435      * If <code>markpos</code> is <code>-1</code>
    436      * (no mark has been set or the mark has been
    437      * invalidated), an <code>IOException</code>
    438      * is thrown. Otherwise, <code>pos</code> is
    439      * set equal to <code>markpos</code>.
    440      *
    441      * @exception  IOException  if this stream has not been marked or,
    442      *                  if the mark has been invalidated, or the stream
    443      *                  has been closed by invoking its {@link #close()}
    444      *                  method, or an I/O error occurs.
    445      * @see        java.io.BufferedInputStream#mark(int)
    446      */
    447     public synchronized void reset() throws IOException {
    448         getBufIfOpen(); // Cause exception if closed
    449         if (markpos < 0)
    450             throw new IOException("Resetting to invalid mark");
    451         pos = markpos;
    452     }
    453 
    454     /**
    455      * Tests if this input stream supports the <code>mark</code>
    456      * and <code>reset</code> methods. The <code>markSupported</code>
    457      * method of <code>BufferedInputStream</code> returns
    458      * <code>true</code>.
    459      *
    460      * @return  a <code>boolean</code> indicating if this stream type supports
    461      *          the <code>mark</code> and <code>reset</code> methods.
    462      * @see     java.io.InputStream#mark(int)
    463      * @see     java.io.InputStream#reset()
    464      */
    465     public boolean markSupported() {
    466         return true;
    467     }
    468 
    469     /**
    470      * Closes this input stream and releases any system resources
    471      * associated with the stream.
    472      * Once the stream has been closed, further read(), available(), reset(),
    473      * or skip() invocations will throw an IOException.
    474      * Closing a previously closed stream has no effect.
    475      *
    476      * @exception  IOException  if an I/O error occurs.
    477      */
    478     public void close() throws IOException {
    479         byte[] buffer;
    480         while ( (buffer = buf) != null) {
    481             if (bufUpdater.compareAndSet(this, buffer, null)) {
    482                 InputStream input = in;
    483                 in = null;
    484                 if (input != null)
    485                     input.close();
    486                 return;
    487             }
    488             // Else retry in case a new buf was CASed in fill()
    489         }
    490     }
    491 }
    492