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