rt/emul/compact/src/main/java/java/io/BufferedInputStream.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 03 Oct 2013 17:36:44 +0200
changeset 1337 c794024954b5
parent 1334 588d5bf7a560
permissions -rw-r--r--
Implementation of few more JDK classes
     1 /*
     2  * Copyright (c) 1994, 2010, 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 
    28 /**
    29  * A <code>BufferedInputStream</code> adds
    30  * functionality to another input stream-namely,
    31  * the ability to buffer the input and to
    32  * support the <code>mark</code> and <code>reset</code>
    33  * methods. When  the <code>BufferedInputStream</code>
    34  * is created, an internal buffer array is
    35  * created. As bytes  from the stream are read
    36  * or skipped, the internal buffer is refilled
    37  * as necessary  from the contained input stream,
    38  * many bytes at a time. The <code>mark</code>
    39  * operation  remembers a point in the input
    40  * stream and the <code>reset</code> operation
    41  * causes all the  bytes read since the most
    42  * recent <code>mark</code> operation to be
    43  * reread before new bytes are  taken from
    44  * the contained input stream.
    45  *
    46  * @author  Arthur van Hoff
    47  * @since   JDK1.0
    48  */
    49 public
    50 class BufferedInputStream extends FilterInputStream {
    51 
    52     private static int defaultBufferSize = 8192;
    53 
    54     /**
    55      * The internal buffer array where the data is stored. When necessary,
    56      * it may be replaced by another array of
    57      * a different size.
    58      */
    59     protected volatile byte buf[];
    60 
    61 
    62     /**
    63      * The index one greater than the index of the last valid byte in
    64      * the buffer.
    65      * This value is always
    66      * in the range <code>0</code> through <code>buf.length</code>;
    67      * elements <code>buf[0]</code>  through <code>buf[count-1]
    68      * </code>contain buffered input data obtained
    69      * from the underlying  input stream.
    70      */
    71     protected int count;
    72 
    73     /**
    74      * The current position in the buffer. This is the index of the next
    75      * character to be read from the <code>buf</code> array.
    76      * <p>
    77      * This value is always in the range <code>0</code>
    78      * through <code>count</code>. If it is less
    79      * than <code>count</code>, then  <code>buf[pos]</code>
    80      * is the next byte to be supplied as input;
    81      * if it is equal to <code>count</code>, then
    82      * the  next <code>read</code> or <code>skip</code>
    83      * operation will require more bytes to be
    84      * read from the contained  input stream.
    85      *
    86      * @see     java.io.BufferedInputStream#buf
    87      */
    88     protected int pos;
    89 
    90     /**
    91      * The value of the <code>pos</code> field at the time the last
    92      * <code>mark</code> method was called.
    93      * <p>
    94      * This value is always
    95      * in the range <code>-1</code> through <code>pos</code>.
    96      * If there is no marked position in  the input
    97      * stream, this field is <code>-1</code>. If
    98      * there is a marked position in the input
    99      * stream,  then <code>buf[markpos]</code>
   100      * is the first byte to be supplied as input
   101      * after a <code>reset</code> operation. If
   102      * <code>markpos</code> is not <code>-1</code>,
   103      * then all bytes from positions <code>buf[markpos]</code>
   104      * through  <code>buf[pos-1]</code> must remain
   105      * in the buffer array (though they may be
   106      * moved to  another place in the buffer array,
   107      * with suitable adjustments to the values
   108      * of <code>count</code>,  <code>pos</code>,
   109      * and <code>markpos</code>); they may not
   110      * be discarded unless and until the difference
   111      * between <code>pos</code> and <code>markpos</code>
   112      * exceeds <code>marklimit</code>.
   113      *
   114      * @see     java.io.BufferedInputStream#mark(int)
   115      * @see     java.io.BufferedInputStream#pos
   116      */
   117     protected int markpos = -1;
   118 
   119     /**
   120      * The maximum read ahead allowed after a call to the
   121      * <code>mark</code> method before subsequent calls to the
   122      * <code>reset</code> method fail.
   123      * Whenever the difference between <code>pos</code>
   124      * and <code>markpos</code> exceeds <code>marklimit</code>,
   125      * then the  mark may be dropped by setting
   126      * <code>markpos</code> to <code>-1</code>.
   127      *
   128      * @see     java.io.BufferedInputStream#mark(int)
   129      * @see     java.io.BufferedInputStream#reset()
   130      */
   131     protected int marklimit;
   132 
   133     /**
   134      * Check to make sure that underlying input stream has not been
   135      * nulled out due to close; if not return it;
   136      */
   137     private InputStream getInIfOpen() throws IOException {
   138         InputStream input = in;
   139         if (input == null)
   140             throw new IOException("Stream closed");
   141         return input;
   142     }
   143 
   144     /**
   145      * Check to make sure that buffer has not been nulled out due to
   146      * close; if not return it;
   147      */
   148     private byte[] getBufIfOpen() throws IOException {
   149         byte[] buffer = buf;
   150         if (buffer == null)
   151             throw new IOException("Stream closed");
   152         return buffer;
   153     }
   154 
   155     /**
   156      * Creates a <code>BufferedInputStream</code>
   157      * and saves its  argument, the input stream
   158      * <code>in</code>, for later use. An internal
   159      * buffer array is created and  stored in <code>buf</code>.
   160      *
   161      * @param   in   the underlying input stream.
   162      */
   163     public BufferedInputStream(InputStream in) {
   164         this(in, defaultBufferSize);
   165     }
   166 
   167     /**
   168      * Creates a <code>BufferedInputStream</code>
   169      * with the specified buffer size,
   170      * and saves its  argument, the input stream
   171      * <code>in</code>, for later use.  An internal
   172      * buffer array of length  <code>size</code>
   173      * is created and stored in <code>buf</code>.
   174      *
   175      * @param   in     the underlying input stream.
   176      * @param   size   the buffer size.
   177      * @exception IllegalArgumentException if size <= 0.
   178      */
   179     public BufferedInputStream(InputStream in, int size) {
   180         super(in);
   181         if (size <= 0) {
   182             throw new IllegalArgumentException("Buffer size <= 0");
   183         }
   184         buf = new byte[size];
   185     }
   186 
   187     /**
   188      * Fills the buffer with more data, taking into account
   189      * shuffling and other tricks for dealing with marks.
   190      * Assumes that it is being called by a synchronized method.
   191      * This method also assumes that all data has already been read in,
   192      * hence pos > count.
   193      */
   194     private void fill() throws IOException {
   195         byte[] buffer = getBufIfOpen();
   196         if (markpos < 0)
   197             pos = 0;            /* no mark: throw away the buffer */
   198         else if (pos >= buffer.length)  /* no room left in buffer */
   199             if (markpos > 0) {  /* can throw away early part of the buffer */
   200                 int sz = pos - markpos;
   201                 System.arraycopy(buffer, markpos, buffer, 0, sz);
   202                 pos = sz;
   203                 markpos = 0;
   204             } else if (buffer.length >= marklimit) {
   205                 markpos = -1;   /* buffer got too big, invalidate mark */
   206                 pos = 0;        /* drop buffer contents */
   207             } else {            /* grow buffer */
   208                 int nsz = pos * 2;
   209                 if (nsz > marklimit)
   210                     nsz = marklimit;
   211                 byte nbuf[] = new byte[nsz];
   212                 System.arraycopy(buffer, 0, nbuf, 0, pos);
   213                 buffer = nbuf;
   214             }
   215         count = pos;
   216         int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
   217         if (n > 0)
   218             count = n + pos;
   219     }
   220 
   221     /**
   222      * See
   223      * the general contract of the <code>read</code>
   224      * method of <code>InputStream</code>.
   225      *
   226      * @return     the next byte of data, or <code>-1</code> if the end of the
   227      *             stream is reached.
   228      * @exception  IOException  if this input stream has been closed by
   229      *                          invoking its {@link #close()} method,
   230      *                          or an I/O error occurs.
   231      * @see        java.io.FilterInputStream#in
   232      */
   233     public synchronized int read() throws IOException {
   234         if (pos >= count) {
   235             fill();
   236             if (pos >= count)
   237                 return -1;
   238         }
   239         return getBufIfOpen()[pos++] & 0xff;
   240     }
   241 
   242     /**
   243      * Read characters into a portion of an array, reading from the underlying
   244      * stream at most once if necessary.
   245      */
   246     private int read1(byte[] b, int off, int len) throws IOException {
   247         int avail = count - pos;
   248         if (avail <= 0) {
   249             /* If the requested length is at least as large as the buffer, and
   250                if there is no mark/reset activity, do not bother to copy the
   251                bytes into the local buffer.  In this way buffered streams will
   252                cascade harmlessly. */
   253             if (len >= getBufIfOpen().length && markpos < 0) {
   254                 return getInIfOpen().read(b, off, len);
   255             }
   256             fill();
   257             avail = count - pos;
   258             if (avail <= 0) return -1;
   259         }
   260         int cnt = (avail < len) ? avail : len;
   261         System.arraycopy(getBufIfOpen(), pos, b, off, cnt);
   262         pos += cnt;
   263         return cnt;
   264     }
   265 
   266     /**
   267      * Reads bytes from this byte-input stream into the specified byte array,
   268      * starting at the given offset.
   269      *
   270      * <p> This method implements the general contract of the corresponding
   271      * <code>{@link InputStream#read(byte[], int, int) read}</code> method of
   272      * the <code>{@link InputStream}</code> class.  As an additional
   273      * convenience, it attempts to read as many bytes as possible by repeatedly
   274      * invoking the <code>read</code> method of the underlying stream.  This
   275      * iterated <code>read</code> continues until one of the following
   276      * conditions becomes true: <ul>
   277      *
   278      *   <li> The specified number of bytes have been read,
   279      *
   280      *   <li> The <code>read</code> method of the underlying stream returns
   281      *   <code>-1</code>, indicating end-of-file, or
   282      *
   283      *   <li> The <code>available</code> method of the underlying stream
   284      *   returns zero, indicating that further input requests would block.
   285      *
   286      * </ul> If the first <code>read</code> on the underlying stream returns
   287      * <code>-1</code> to indicate end-of-file then this method returns
   288      * <code>-1</code>.  Otherwise this method returns the number of bytes
   289      * actually read.
   290      *
   291      * <p> Subclasses of this class are encouraged, but not required, to
   292      * attempt to read as many bytes as possible in the same fashion.
   293      *
   294      * @param      b     destination buffer.
   295      * @param      off   offset at which to start storing bytes.
   296      * @param      len   maximum number of bytes to read.
   297      * @return     the number of bytes read, or <code>-1</code> if the end of
   298      *             the stream has been reached.
   299      * @exception  IOException  if this input stream has been closed by
   300      *                          invoking its {@link #close()} method,
   301      *                          or an I/O error occurs.
   302      */
   303     public synchronized int read(byte b[], int off, int len)
   304         throws IOException
   305     {
   306         getBufIfOpen(); // Check for closed stream
   307         if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
   308             throw new IndexOutOfBoundsException();
   309         } else if (len == 0) {
   310             return 0;
   311         }
   312 
   313         int n = 0;
   314         for (;;) {
   315             int nread = read1(b, off + n, len - n);
   316             if (nread <= 0)
   317                 return (n == 0) ? nread : n;
   318             n += nread;
   319             if (n >= len)
   320                 return n;
   321             // if not closed but no bytes available, return
   322             InputStream input = in;
   323             if (input != null && input.available() <= 0)
   324                 return n;
   325         }
   326     }
   327 
   328     /**
   329      * See the general contract of the <code>skip</code>
   330      * method of <code>InputStream</code>.
   331      *
   332      * @exception  IOException  if the stream does not support seek,
   333      *                          or if this input stream has been closed by
   334      *                          invoking its {@link #close()} method, or an
   335      *                          I/O error occurs.
   336      */
   337     public synchronized long skip(long n) throws IOException {
   338         getBufIfOpen(); // Check for closed stream
   339         if (n <= 0) {
   340             return 0;
   341         }
   342         long avail = count - pos;
   343 
   344         if (avail <= 0) {
   345             // If no mark position set then don't keep in buffer
   346             if (markpos <0)
   347                 return getInIfOpen().skip(n);
   348 
   349             // Fill in buffer to save bytes for reset
   350             fill();
   351             avail = count - pos;
   352             if (avail <= 0)
   353                 return 0;
   354         }
   355 
   356         long skipped = (avail < n) ? avail : n;
   357         pos += skipped;
   358         return skipped;
   359     }
   360 
   361     /**
   362      * Returns an estimate of the number of bytes that can be read (or
   363      * skipped over) from this input stream without blocking by the next
   364      * invocation of a method for this input stream. The next invocation might be
   365      * the same thread or another thread.  A single read or skip of this
   366      * many bytes will not block, but may read or skip fewer bytes.
   367      * <p>
   368      * This method returns the sum of the number of bytes remaining to be read in
   369      * the buffer (<code>count&nbsp;- pos</code>) and the result of calling the
   370      * {@link java.io.FilterInputStream#in in}.available().
   371      *
   372      * @return     an estimate of the number of bytes that can be read (or skipped
   373      *             over) from this input stream without blocking.
   374      * @exception  IOException  if this input stream has been closed by
   375      *                          invoking its {@link #close()} method,
   376      *                          or an I/O error occurs.
   377      */
   378     public synchronized int available() throws IOException {
   379         int n = count - pos;
   380         int avail = getInIfOpen().available();
   381         return n > (Integer.MAX_VALUE - avail)
   382                     ? Integer.MAX_VALUE
   383                     : n + avail;
   384     }
   385 
   386     /**
   387      * See the general contract of the <code>mark</code>
   388      * method of <code>InputStream</code>.
   389      *
   390      * @param   readlimit   the maximum limit of bytes that can be read before
   391      *                      the mark position becomes invalid.
   392      * @see     java.io.BufferedInputStream#reset()
   393      */
   394     public synchronized void mark(int readlimit) {
   395         marklimit = readlimit;
   396         markpos = pos;
   397     }
   398 
   399     /**
   400      * See the general contract of the <code>reset</code>
   401      * method of <code>InputStream</code>.
   402      * <p>
   403      * If <code>markpos</code> is <code>-1</code>
   404      * (no mark has been set or the mark has been
   405      * invalidated), an <code>IOException</code>
   406      * is thrown. Otherwise, <code>pos</code> is
   407      * set equal to <code>markpos</code>.
   408      *
   409      * @exception  IOException  if this stream has not been marked or,
   410      *                  if the mark has been invalidated, or the stream
   411      *                  has been closed by invoking its {@link #close()}
   412      *                  method, or an I/O error occurs.
   413      * @see        java.io.BufferedInputStream#mark(int)
   414      */
   415     public synchronized void reset() throws IOException {
   416         getBufIfOpen(); // Cause exception if closed
   417         if (markpos < 0)
   418             throw new IOException("Resetting to invalid mark");
   419         pos = markpos;
   420     }
   421 
   422     /**
   423      * Tests if this input stream supports the <code>mark</code>
   424      * and <code>reset</code> methods. The <code>markSupported</code>
   425      * method of <code>BufferedInputStream</code> returns
   426      * <code>true</code>.
   427      *
   428      * @return  a <code>boolean</code> indicating if this stream type supports
   429      *          the <code>mark</code> and <code>reset</code> methods.
   430      * @see     java.io.InputStream#mark(int)
   431      * @see     java.io.InputStream#reset()
   432      */
   433     public boolean markSupported() {
   434         return true;
   435     }
   436 
   437     /**
   438      * Closes this input stream and releases any system resources
   439      * associated with the stream.
   440      * Once the stream has been closed, further read(), available(), reset(),
   441      * or skip() invocations will throw an IOException.
   442      * Closing a previously closed stream has no effect.
   443      *
   444      * @exception  IOException  if an I/O error occurs.
   445      */
   446     public void close() throws IOException {
   447         byte[] buffer;
   448         while ( (buffer = buf) != null) {
   449             InputStream input = in;
   450             buf = null;
   451             in = null;
   452             if (input != null)
   453                 input.close();
   454             return;
   455             // Else retry in case a new buf was CASed in fill()
   456         }
   457     }
   458 }