/* BufferedReader.java Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.io; /* Written using "Java Class Libraries", 2nd edition, plus online * API docs for JDK 1.2 beta from http://www.javasoft.com. * Status: Believed complete and correct. */ /** * This subclass of FilterReader buffers input from an * underlying implementation to provide a possibly more efficient read * mechanism. It maintains the buffer and buffer state in instance * variables that are available to subclasses. The default buffer size * of 8192 chars can be overridden by the creator of the stream. *

* This class also implements mark/reset functionality. It is capable * of remembering any number of input chars, to the limits of * system memory or the size of Integer.MAX_VALUE * * @author Per Bothner * @author Aaron M. Renn */ public class BufferedReader extends Reader { Reader in; char[] buffer; /* Index of current read position. Must be >= 0 and <= limit. */ int pos; /* Limit of valid data in buffer. Must be >= pos and <= buffer.length. */ int limit; /* The value -1 means there is no mark, or the mark has been invalidated. Otherwise, markPos is the index in the buffer of the marked position. Must be >= 0 and <= pos. */ int markPos = -1; /* Maximum number of characters that can be read before markPos becomes invalid. */ int markLimit = -1; // The JCL book specifies the default buffer size as 8K characters. // This is package-private because it is used by LineNumberReader. static final int DEFAULT_BUFFER_SIZE = 8192; /** * Create a new BufferedReader that will read from the * specified subordinate stream with a default buffer size of 8192 chars. * * @param in The subordinate stream to read from */ public BufferedReader(Reader in) { this(in, DEFAULT_BUFFER_SIZE); } /** * Create a new BufferedReader that will read from the * specified subordinate stream with a buffer size that is specified by the * caller. * * @param in The subordinate stream to read from * @param size The buffer size to use */ public BufferedReader(Reader in, int size) { super(in.lock); this.in = in; buffer = new char[size]; } /** * This method closes the underlying stream and frees any associated * resources. * * @exception IOException If an error occurs */ public void close() throws IOException { synchronized (lock) { if (in != null) in.close(); in = null; buffer = null; } } /** * Returns true to indicate that this class supports mark/reset * functionality. * * @return true */ public boolean markSupported() { return true; } /** * Mark a position in the input to which the stream can be * "reset" by calling the reset() method. The parameter * readLimit is the number of chars that can be read from the * stream after setting the mark before the mark becomes invalid. For * example, if mark() is called with a read limit of 10, then * when 11 chars of data are read from the stream before the * reset() method is called, then the mark is invalid and the * stream object instance is not required to remember the mark. *

* Note that the number of chars that can be remembered by this method * can be greater than the size of the internal read buffer. It is also * not dependent on the subordinate stream supporting mark/reset * functionality. * * @param readLimit The number of chars that can be read before the mark * becomes invalid * * @exception IOException If an error occurs */ public void mark(int readLimit) throws IOException { if (readLimit < 0) throw new IllegalArgumentException(); synchronized (lock) { checkStatus(); markPos = pos; markLimit = readLimit; } } /** * Reset the stream to the point where the mark() method * was called. Any chars that were read after the mark point was set will * be re-read during subsequent reads. *

* This method will throw an IOException if the number of chars read from * the stream since the call to mark() exceeds the mark limit * passed when establishing the mark. * * @exception IOException If an error occurs; */ public void reset() throws IOException { synchronized (lock) { checkStatus(); if (markPos < 0) throw new IOException("mark never set or invalidated"); pos = markPos; } } /** * This method determines whether or not a stream is ready to be read. If * this method returns false then this stream could (but is * not guaranteed to) block on the next read attempt. * * @return true if this stream is ready to be read, * false otherwise * * @exception IOException If an error occurs */ public boolean ready() throws IOException { synchronized (lock) { checkStatus(); return pos < limit || in.ready(); } } /** * This method read chars from a stream and stores them into a caller * supplied buffer. It starts storing the data at index * offset into * the buffer and attempts to read len chars. This method can * return before reading the number of chars requested. The actual number * of chars read is returned as an int. A -1 is returned to indicate the * end of the stream. *

* This method will block until some data can be read. * * @param buf The array into which the chars read should be stored * @param offset The offset into the array to start storing chars * @param count The requested number of chars to read * * @return The actual number of chars read, or -1 if end of stream. * * @exception IOException If an error occurs. */ public int read(char[] buf, int offset, int count) throws IOException { synchronized (lock) { checkStatus(); if (pos == limit && !refill()) return -1; int charsTotal = 0; while (true) { int charsInBuffer = limit - pos; int charsToRead = Math.min(charsInBuffer, count - charsTotal); System.arraycopy(buffer, pos, buf, offset, charsToRead); offset += charsToRead; pos += charsToRead; charsTotal += charsToRead; if (charsTotal == count || !refill()) return charsTotal; } } } /** Read more data into the buffer, updating pos and limit appropriately, * and taking mark and markLimit into account. Assumes pos==limit initially. * Return true if chars were added to the buffer, or false on EOF. */ private boolean refill() throws IOException { // Check for invalidated mark. if (markPos >= 0 && pos - markPos > markLimit) markPos = -1; if (markPos < 0) limit = pos = 0; else if (markPos > 0) { // Shift marked bytes (if any) to the beginning of the array. System.arraycopy(buffer, markPos, buffer, 0, limit - markPos); limit -= markPos; pos -= markPos; markPos = 0; } else if (markLimit >= buffer.length) // markPos == 0 { // Need to grow the buffer now to have room for markLimit bytes. // Note that the new buffer is one greater than markLimit. // This is so that there will be one byte past marklimit to be read // before having to call refill again, thus allowing marklimit to be // invalidated. That way refill doesn't have to check marklimit. char[] new_buffer = new char[markLimit + 1]; System.arraycopy(buffer, 0, new_buffer, 0, limit); buffer = new_buffer; } int limitOrig = limit; int count; do { count = in.read(buffer, limit, buffer.length - limit); if (count == -1) break; limit += count; } while (limit < buffer.length && in.ready()); if (count == -1 && limitOrig == limit) return false; return true; } public int read() throws IOException { synchronized (lock) { checkStatus(); if (pos == limit && !refill()) return -1; return buffer[pos++]; } } /** * Read a single line of text from the input stream, returning * it as a String. A line is terminated by "\n", a "\r", or * an "\r\n" sequence. The system dependent line separator is not used. * The line termination characters are not returned in the resulting * String. * * @return The line of text read, or null if end of stream. * * @exception IOException If an error occurs */ public String readLine() throws IOException { synchronized (lock) { checkStatus(); if (pos == limit && !refill()) return null; StringBuffer sbuf = null; String result = null; while (result == null) { int len = -1; int i = pos; char ch = '\0'; for (; i < limit; i++) { ch = buffer[i]; if (ch == '\n' || ch == '\r') { len = i - pos; break; } } if (len >= 0) { // Found end of line. if (sbuf == null) result = new String(buffer, pos, len); else { sbuf.append(buffer, pos, len); result = sbuf.toString(); } // Consume the line termination character(s). pos = i + 1; if (ch == '\r') { if (pos == limit) { // Special case: refill the buffer to check for a // '\r\n' sequence that crosses the buffer boundary. if (!refill()) break; } if (buffer[pos] == '\n') pos++; } } else { // Reached limit of buffer. Store chars in StringBuffer and // refill. if (sbuf == null) sbuf = new StringBuffer(len + 48); sbuf.append(buffer, pos, limit - pos); pos = limit; if (!refill()) result = sbuf.toString(); } } return result; } } /** * This method skips the specified number of chars in the stream. It * returns the actual number of chars skipped, which may be less than the * requested amount. *

* This method first discards chars in the buffer, then calls the * skip method on the underlying stream to skip the * remaining chars. * * @param numChars The requested number of chars to skip * * @return The actual number of chars skipped. * * @exception IOException If an error occurs */ public long skip(long count) throws IOException { synchronized (lock) { checkStatus(); final long origCount = count; while (count > 0) { if (pos == limit && !refill()) if (count < origCount) break; else return -1; // No chars were read before EOF. int numread = (int) Math.min((long) (limit - pos), count); pos += numread; count -= numread; } return origCount - count; } } private void checkStatus() throws IOException { if (in == null) throw new IOException("Stream closed"); } }