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