1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/rt/emul/compact/src/main/java/java/io/BufferedInputStream.java Thu Oct 03 15:40:35 2013 +0200
1.3 @@ -0,0 +1,478 @@
1.4 +/*
1.5 + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1.7 + *
1.8 + * This code is free software; you can redistribute it and/or modify it
1.9 + * under the terms of the GNU General Public License version 2 only, as
1.10 + * published by the Free Software Foundation. Oracle designates this
1.11 + * particular file as subject to the "Classpath" exception as provided
1.12 + * by Oracle in the LICENSE file that accompanied this code.
1.13 + *
1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1.17 + * version 2 for more details (a copy is included in the LICENSE file that
1.18 + * accompanied this code).
1.19 + *
1.20 + * You should have received a copy of the GNU General Public License version
1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1.23 + *
1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1.25 + * or visit www.oracle.com if you need additional information or have any
1.26 + * questions.
1.27 + */
1.28 +
1.29 +package java.io;
1.30 +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
1.31 +
1.32 +/**
1.33 + * A <code>BufferedInputStream</code> adds
1.34 + * functionality to another input stream-namely,
1.35 + * the ability to buffer the input and to
1.36 + * support the <code>mark</code> and <code>reset</code>
1.37 + * methods. When the <code>BufferedInputStream</code>
1.38 + * is created, an internal buffer array is
1.39 + * created. As bytes from the stream are read
1.40 + * or skipped, the internal buffer is refilled
1.41 + * as necessary from the contained input stream,
1.42 + * many bytes at a time. The <code>mark</code>
1.43 + * operation remembers a point in the input
1.44 + * stream and the <code>reset</code> operation
1.45 + * causes all the bytes read since the most
1.46 + * recent <code>mark</code> operation to be
1.47 + * reread before new bytes are taken from
1.48 + * the contained input stream.
1.49 + *
1.50 + * @author Arthur van Hoff
1.51 + * @since JDK1.0
1.52 + */
1.53 +public
1.54 +class BufferedInputStream extends FilterInputStream {
1.55 +
1.56 + private static int defaultBufferSize = 8192;
1.57 +
1.58 + /**
1.59 + * The internal buffer array where the data is stored. When necessary,
1.60 + * it may be replaced by another array of
1.61 + * a different size.
1.62 + */
1.63 + protected volatile byte buf[];
1.64 +
1.65 + /**
1.66 + * Atomic updater to provide compareAndSet for buf. This is
1.67 + * necessary because closes can be asynchronous. We use nullness
1.68 + * of buf[] as primary indicator that this stream is closed. (The
1.69 + * "in" field is also nulled out on close.)
1.70 + */
1.71 + private static final
1.72 + AtomicReferenceFieldUpdater<BufferedInputStream, byte[]> bufUpdater =
1.73 + AtomicReferenceFieldUpdater.newUpdater
1.74 + (BufferedInputStream.class, byte[].class, "buf");
1.75 +
1.76 + /**
1.77 + * The index one greater than the index of the last valid byte in
1.78 + * the buffer.
1.79 + * This value is always
1.80 + * in the range <code>0</code> through <code>buf.length</code>;
1.81 + * elements <code>buf[0]</code> through <code>buf[count-1]
1.82 + * </code>contain buffered input data obtained
1.83 + * from the underlying input stream.
1.84 + */
1.85 + protected int count;
1.86 +
1.87 + /**
1.88 + * The current position in the buffer. This is the index of the next
1.89 + * character to be read from the <code>buf</code> array.
1.90 + * <p>
1.91 + * This value is always in the range <code>0</code>
1.92 + * through <code>count</code>. If it is less
1.93 + * than <code>count</code>, then <code>buf[pos]</code>
1.94 + * is the next byte to be supplied as input;
1.95 + * if it is equal to <code>count</code>, then
1.96 + * the next <code>read</code> or <code>skip</code>
1.97 + * operation will require more bytes to be
1.98 + * read from the contained input stream.
1.99 + *
1.100 + * @see java.io.BufferedInputStream#buf
1.101 + */
1.102 + protected int pos;
1.103 +
1.104 + /**
1.105 + * The value of the <code>pos</code> field at the time the last
1.106 + * <code>mark</code> method was called.
1.107 + * <p>
1.108 + * This value is always
1.109 + * in the range <code>-1</code> through <code>pos</code>.
1.110 + * If there is no marked position in the input
1.111 + * stream, this field is <code>-1</code>. If
1.112 + * there is a marked position in the input
1.113 + * stream, then <code>buf[markpos]</code>
1.114 + * is the first byte to be supplied as input
1.115 + * after a <code>reset</code> operation. If
1.116 + * <code>markpos</code> is not <code>-1</code>,
1.117 + * then all bytes from positions <code>buf[markpos]</code>
1.118 + * through <code>buf[pos-1]</code> must remain
1.119 + * in the buffer array (though they may be
1.120 + * moved to another place in the buffer array,
1.121 + * with suitable adjustments to the values
1.122 + * of <code>count</code>, <code>pos</code>,
1.123 + * and <code>markpos</code>); they may not
1.124 + * be discarded unless and until the difference
1.125 + * between <code>pos</code> and <code>markpos</code>
1.126 + * exceeds <code>marklimit</code>.
1.127 + *
1.128 + * @see java.io.BufferedInputStream#mark(int)
1.129 + * @see java.io.BufferedInputStream#pos
1.130 + */
1.131 + protected int markpos = -1;
1.132 +
1.133 + /**
1.134 + * The maximum read ahead allowed after a call to the
1.135 + * <code>mark</code> method before subsequent calls to the
1.136 + * <code>reset</code> method fail.
1.137 + * Whenever the difference between <code>pos</code>
1.138 + * and <code>markpos</code> exceeds <code>marklimit</code>,
1.139 + * then the mark may be dropped by setting
1.140 + * <code>markpos</code> to <code>-1</code>.
1.141 + *
1.142 + * @see java.io.BufferedInputStream#mark(int)
1.143 + * @see java.io.BufferedInputStream#reset()
1.144 + */
1.145 + protected int marklimit;
1.146 +
1.147 + /**
1.148 + * Check to make sure that underlying input stream has not been
1.149 + * nulled out due to close; if not return it;
1.150 + */
1.151 + private InputStream getInIfOpen() throws IOException {
1.152 + InputStream input = in;
1.153 + if (input == null)
1.154 + throw new IOException("Stream closed");
1.155 + return input;
1.156 + }
1.157 +
1.158 + /**
1.159 + * Check to make sure that buffer has not been nulled out due to
1.160 + * close; if not return it;
1.161 + */
1.162 + private byte[] getBufIfOpen() throws IOException {
1.163 + byte[] buffer = buf;
1.164 + if (buffer == null)
1.165 + throw new IOException("Stream closed");
1.166 + return buffer;
1.167 + }
1.168 +
1.169 + /**
1.170 + * Creates a <code>BufferedInputStream</code>
1.171 + * and saves its argument, the input stream
1.172 + * <code>in</code>, for later use. An internal
1.173 + * buffer array is created and stored in <code>buf</code>.
1.174 + *
1.175 + * @param in the underlying input stream.
1.176 + */
1.177 + public BufferedInputStream(InputStream in) {
1.178 + this(in, defaultBufferSize);
1.179 + }
1.180 +
1.181 + /**
1.182 + * Creates a <code>BufferedInputStream</code>
1.183 + * with the specified buffer size,
1.184 + * and saves its argument, the input stream
1.185 + * <code>in</code>, for later use. An internal
1.186 + * buffer array of length <code>size</code>
1.187 + * is created and stored in <code>buf</code>.
1.188 + *
1.189 + * @param in the underlying input stream.
1.190 + * @param size the buffer size.
1.191 + * @exception IllegalArgumentException if size <= 0.
1.192 + */
1.193 + public BufferedInputStream(InputStream in, int size) {
1.194 + super(in);
1.195 + if (size <= 0) {
1.196 + throw new IllegalArgumentException("Buffer size <= 0");
1.197 + }
1.198 + buf = new byte[size];
1.199 + }
1.200 +
1.201 + /**
1.202 + * Fills the buffer with more data, taking into account
1.203 + * shuffling and other tricks for dealing with marks.
1.204 + * Assumes that it is being called by a synchronized method.
1.205 + * This method also assumes that all data has already been read in,
1.206 + * hence pos > count.
1.207 + */
1.208 + private void fill() throws IOException {
1.209 + byte[] buffer = getBufIfOpen();
1.210 + if (markpos < 0)
1.211 + pos = 0; /* no mark: throw away the buffer */
1.212 + else if (pos >= buffer.length) /* no room left in buffer */
1.213 + if (markpos > 0) { /* can throw away early part of the buffer */
1.214 + int sz = pos - markpos;
1.215 + System.arraycopy(buffer, markpos, buffer, 0, sz);
1.216 + pos = sz;
1.217 + markpos = 0;
1.218 + } else if (buffer.length >= marklimit) {
1.219 + markpos = -1; /* buffer got too big, invalidate mark */
1.220 + pos = 0; /* drop buffer contents */
1.221 + } else { /* grow buffer */
1.222 + int nsz = pos * 2;
1.223 + if (nsz > marklimit)
1.224 + nsz = marklimit;
1.225 + byte nbuf[] = new byte[nsz];
1.226 + System.arraycopy(buffer, 0, nbuf, 0, pos);
1.227 + if (!bufUpdater.compareAndSet(this, buffer, nbuf)) {
1.228 + // Can't replace buf if there was an async close.
1.229 + // Note: This would need to be changed if fill()
1.230 + // is ever made accessible to multiple threads.
1.231 + // But for now, the only way CAS can fail is via close.
1.232 + // assert buf == null;
1.233 + throw new IOException("Stream closed");
1.234 + }
1.235 + buffer = nbuf;
1.236 + }
1.237 + count = pos;
1.238 + int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
1.239 + if (n > 0)
1.240 + count = n + pos;
1.241 + }
1.242 +
1.243 + /**
1.244 + * See
1.245 + * the general contract of the <code>read</code>
1.246 + * method of <code>InputStream</code>.
1.247 + *
1.248 + * @return the next byte of data, or <code>-1</code> if the end of the
1.249 + * stream is reached.
1.250 + * @exception IOException if this input stream has been closed by
1.251 + * invoking its {@link #close()} method,
1.252 + * or an I/O error occurs.
1.253 + * @see java.io.FilterInputStream#in
1.254 + */
1.255 + public synchronized int read() throws IOException {
1.256 + if (pos >= count) {
1.257 + fill();
1.258 + if (pos >= count)
1.259 + return -1;
1.260 + }
1.261 + return getBufIfOpen()[pos++] & 0xff;
1.262 + }
1.263 +
1.264 + /**
1.265 + * Read characters into a portion of an array, reading from the underlying
1.266 + * stream at most once if necessary.
1.267 + */
1.268 + private int read1(byte[] b, int off, int len) throws IOException {
1.269 + int avail = count - pos;
1.270 + if (avail <= 0) {
1.271 + /* If the requested length is at least as large as the buffer, and
1.272 + if there is no mark/reset activity, do not bother to copy the
1.273 + bytes into the local buffer. In this way buffered streams will
1.274 + cascade harmlessly. */
1.275 + if (len >= getBufIfOpen().length && markpos < 0) {
1.276 + return getInIfOpen().read(b, off, len);
1.277 + }
1.278 + fill();
1.279 + avail = count - pos;
1.280 + if (avail <= 0) return -1;
1.281 + }
1.282 + int cnt = (avail < len) ? avail : len;
1.283 + System.arraycopy(getBufIfOpen(), pos, b, off, cnt);
1.284 + pos += cnt;
1.285 + return cnt;
1.286 + }
1.287 +
1.288 + /**
1.289 + * Reads bytes from this byte-input stream into the specified byte array,
1.290 + * starting at the given offset.
1.291 + *
1.292 + * <p> This method implements the general contract of the corresponding
1.293 + * <code>{@link InputStream#read(byte[], int, int) read}</code> method of
1.294 + * the <code>{@link InputStream}</code> class. As an additional
1.295 + * convenience, it attempts to read as many bytes as possible by repeatedly
1.296 + * invoking the <code>read</code> method of the underlying stream. This
1.297 + * iterated <code>read</code> continues until one of the following
1.298 + * conditions becomes true: <ul>
1.299 + *
1.300 + * <li> The specified number of bytes have been read,
1.301 + *
1.302 + * <li> The <code>read</code> method of the underlying stream returns
1.303 + * <code>-1</code>, indicating end-of-file, or
1.304 + *
1.305 + * <li> The <code>available</code> method of the underlying stream
1.306 + * returns zero, indicating that further input requests would block.
1.307 + *
1.308 + * </ul> If the first <code>read</code> on the underlying stream returns
1.309 + * <code>-1</code> to indicate end-of-file then this method returns
1.310 + * <code>-1</code>. Otherwise this method returns the number of bytes
1.311 + * actually read.
1.312 + *
1.313 + * <p> Subclasses of this class are encouraged, but not required, to
1.314 + * attempt to read as many bytes as possible in the same fashion.
1.315 + *
1.316 + * @param b destination buffer.
1.317 + * @param off offset at which to start storing bytes.
1.318 + * @param len maximum number of bytes to read.
1.319 + * @return the number of bytes read, or <code>-1</code> if the end of
1.320 + * the stream has been reached.
1.321 + * @exception IOException if this input stream has been closed by
1.322 + * invoking its {@link #close()} method,
1.323 + * or an I/O error occurs.
1.324 + */
1.325 + public synchronized int read(byte b[], int off, int len)
1.326 + throws IOException
1.327 + {
1.328 + getBufIfOpen(); // Check for closed stream
1.329 + if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
1.330 + throw new IndexOutOfBoundsException();
1.331 + } else if (len == 0) {
1.332 + return 0;
1.333 + }
1.334 +
1.335 + int n = 0;
1.336 + for (;;) {
1.337 + int nread = read1(b, off + n, len - n);
1.338 + if (nread <= 0)
1.339 + return (n == 0) ? nread : n;
1.340 + n += nread;
1.341 + if (n >= len)
1.342 + return n;
1.343 + // if not closed but no bytes available, return
1.344 + InputStream input = in;
1.345 + if (input != null && input.available() <= 0)
1.346 + return n;
1.347 + }
1.348 + }
1.349 +
1.350 + /**
1.351 + * See the general contract of the <code>skip</code>
1.352 + * method of <code>InputStream</code>.
1.353 + *
1.354 + * @exception IOException if the stream does not support seek,
1.355 + * or if this input stream has been closed by
1.356 + * invoking its {@link #close()} method, or an
1.357 + * I/O error occurs.
1.358 + */
1.359 + public synchronized long skip(long n) throws IOException {
1.360 + getBufIfOpen(); // Check for closed stream
1.361 + if (n <= 0) {
1.362 + return 0;
1.363 + }
1.364 + long avail = count - pos;
1.365 +
1.366 + if (avail <= 0) {
1.367 + // If no mark position set then don't keep in buffer
1.368 + if (markpos <0)
1.369 + return getInIfOpen().skip(n);
1.370 +
1.371 + // Fill in buffer to save bytes for reset
1.372 + fill();
1.373 + avail = count - pos;
1.374 + if (avail <= 0)
1.375 + return 0;
1.376 + }
1.377 +
1.378 + long skipped = (avail < n) ? avail : n;
1.379 + pos += skipped;
1.380 + return skipped;
1.381 + }
1.382 +
1.383 + /**
1.384 + * Returns an estimate of the number of bytes that can be read (or
1.385 + * skipped over) from this input stream without blocking by the next
1.386 + * invocation of a method for this input stream. The next invocation might be
1.387 + * the same thread or another thread. A single read or skip of this
1.388 + * many bytes will not block, but may read or skip fewer bytes.
1.389 + * <p>
1.390 + * This method returns the sum of the number of bytes remaining to be read in
1.391 + * the buffer (<code>count - pos</code>) and the result of calling the
1.392 + * {@link java.io.FilterInputStream#in in}.available().
1.393 + *
1.394 + * @return an estimate of the number of bytes that can be read (or skipped
1.395 + * over) from this input stream without blocking.
1.396 + * @exception IOException if this input stream has been closed by
1.397 + * invoking its {@link #close()} method,
1.398 + * or an I/O error occurs.
1.399 + */
1.400 + public synchronized int available() throws IOException {
1.401 + int n = count - pos;
1.402 + int avail = getInIfOpen().available();
1.403 + return n > (Integer.MAX_VALUE - avail)
1.404 + ? Integer.MAX_VALUE
1.405 + : n + avail;
1.406 + }
1.407 +
1.408 + /**
1.409 + * See the general contract of the <code>mark</code>
1.410 + * method of <code>InputStream</code>.
1.411 + *
1.412 + * @param readlimit the maximum limit of bytes that can be read before
1.413 + * the mark position becomes invalid.
1.414 + * @see java.io.BufferedInputStream#reset()
1.415 + */
1.416 + public synchronized void mark(int readlimit) {
1.417 + marklimit = readlimit;
1.418 + markpos = pos;
1.419 + }
1.420 +
1.421 + /**
1.422 + * See the general contract of the <code>reset</code>
1.423 + * method of <code>InputStream</code>.
1.424 + * <p>
1.425 + * If <code>markpos</code> is <code>-1</code>
1.426 + * (no mark has been set or the mark has been
1.427 + * invalidated), an <code>IOException</code>
1.428 + * is thrown. Otherwise, <code>pos</code> is
1.429 + * set equal to <code>markpos</code>.
1.430 + *
1.431 + * @exception IOException if this stream has not been marked or,
1.432 + * if the mark has been invalidated, or the stream
1.433 + * has been closed by invoking its {@link #close()}
1.434 + * method, or an I/O error occurs.
1.435 + * @see java.io.BufferedInputStream#mark(int)
1.436 + */
1.437 + public synchronized void reset() throws IOException {
1.438 + getBufIfOpen(); // Cause exception if closed
1.439 + if (markpos < 0)
1.440 + throw new IOException("Resetting to invalid mark");
1.441 + pos = markpos;
1.442 + }
1.443 +
1.444 + /**
1.445 + * Tests if this input stream supports the <code>mark</code>
1.446 + * and <code>reset</code> methods. The <code>markSupported</code>
1.447 + * method of <code>BufferedInputStream</code> returns
1.448 + * <code>true</code>.
1.449 + *
1.450 + * @return a <code>boolean</code> indicating if this stream type supports
1.451 + * the <code>mark</code> and <code>reset</code> methods.
1.452 + * @see java.io.InputStream#mark(int)
1.453 + * @see java.io.InputStream#reset()
1.454 + */
1.455 + public boolean markSupported() {
1.456 + return true;
1.457 + }
1.458 +
1.459 + /**
1.460 + * Closes this input stream and releases any system resources
1.461 + * associated with the stream.
1.462 + * Once the stream has been closed, further read(), available(), reset(),
1.463 + * or skip() invocations will throw an IOException.
1.464 + * Closing a previously closed stream has no effect.
1.465 + *
1.466 + * @exception IOException if an I/O error occurs.
1.467 + */
1.468 + public void close() throws IOException {
1.469 + byte[] buffer;
1.470 + while ( (buffer = buf) != null) {
1.471 + if (bufUpdater.compareAndSet(this, buffer, null)) {
1.472 + InputStream input = in;
1.473 + in = null;
1.474 + if (input != null)
1.475 + input.close();
1.476 + return;
1.477 + }
1.478 + // Else retry in case a new buf was CASed in fill()
1.479 + }
1.480 + }
1.481 +}