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