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