comparison src/goodjava/io/BufferedInputStream.java @ 1478:37e582f2e266

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