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