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