FSF GCC merge 02/23/03
[official-gcc.git] / libjava / java / io / BufferedReader.java
blobb4cdb639b4333ed9ff0923c525c8f16c3dedd997
1 /* BufferedReader.java
2 Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
39 package java.io;
41 /* Written using "Java Class Libraries", 2nd edition, plus online
42 * API docs for JDK 1.2 beta from http://www.javasoft.com.
43 * Status: Believed complete and correct.
46 /**
47 * This subclass of <code>FilterReader</code> buffers input from an
48 * underlying implementation to provide a possibly more efficient read
49 * mechanism. It maintains the buffer and buffer state in instance
50 * variables that are available to subclasses. The default buffer size
51 * of 512 chars can be overridden by the creator of the stream.
52 * <p>
53 * This class also implements mark/reset functionality. It is capable
54 * of remembering any number of input chars, to the limits of
55 * system memory or the size of <code>Integer.MAX_VALUE</code>
57 * @author Per Bothner <bothner@cygnus.com>
58 * @author Aaron M. Renn <arenn@urbanophile.com>
60 public class BufferedReader extends Reader
62 Reader in;
63 char[] buffer;
64 /* Index of current read position. Must be >= 0 and <= limit. */
65 /* There is a special case where pos may be equal to limit+1; this
66 * is used as an indicator that a readLine was done with a '\r' was
67 * the very last char in the buffer. Since we don't want to read-ahead
68 * and potentially block, we set pos this way to indicate the situation
69 * and deal with it later. Doing it this way rather than having a
70 * separate boolean field to indicate the condition has the advantage
71 * that it is self-clearing on things like mark/reset.
73 int pos;
74 /* Limit of valid data in buffer. Must be >= pos and <= buffer.length. */
75 /* This can be < pos in the one special case described above. */
76 int limit;
78 /* The value -1 means there is no mark, or the mark has been invalidated.
79 Otherwise, markPos is the index in the buffer of the marked position.
80 Must be >= 0 and <= pos.
81 Note we do not explicitly store the read-limit.
82 The implicit read-limit is (buffer.length - markPos), which is
83 guaranteed to be >= the read-limit requested in the call to mark. */
84 int markPos = -1;
86 // The JCL book specifies the default buffer size as 8K characters.
87 // This is package-private because it is used by LineNumberReader.
88 static final int DEFAULT_BUFFER_SIZE = 8192;
90 /**
91 * Create a new <code>BufferedReader</code> that will read from the
92 * specified subordinate stream with a default buffer size of 4096 chars.
94 * @param in The subordinate stream to read from
96 public BufferedReader(Reader in)
98 this(in, DEFAULT_BUFFER_SIZE);
102 * Create a new <code>BufferedReader</code> that will read from the
103 * specified subordinate stream with a buffer size that is specified by the
104 * caller.
106 * @param in The subordinate stream to read from
107 * @param bufsize The buffer size to use
109 public BufferedReader(Reader in, int size)
111 super(in.lock);
112 this.in = in;
113 buffer = new char[size];
117 * This method closes the stream
119 * @exception IOException If an error occurs
121 public void close() throws IOException
123 synchronized (lock)
125 if (in != null)
126 in.close();
127 in = null;
128 buffer = null;
133 * Returns <code>true</code> to indicate that this class supports mark/reset
134 * functionality.
136 * @return <code>true</code>
138 public boolean markSupported()
140 return true;
144 * Mark a position in the input to which the stream can be
145 * "reset" by calling the <code>reset()</code> method. The parameter
146 * <code>readlimit</code> is the number of chars that can be read from the
147 * stream after setting the mark before the mark becomes invalid. For
148 * example, if <code>mark()</code> is called with a read limit of 10, then
149 * when 11 chars of data are read from the stream before the
150 * <code>reset()</code> method is called, then the mark is invalid and the
151 * stream object instance is not required to remember the mark.
152 * <p>
153 * Note that the number of chars that can be remembered by this method
154 * can be greater than the size of the internal read buffer. It is also
155 * not dependent on the subordinate stream supporting mark/reset
156 * functionality.
158 * @param readlimit The number of chars that can be read before the mark
159 * becomes invalid
161 * @exception IOException If an error occurs
163 public void mark(int readLimit) throws IOException
165 synchronized (lock)
167 checkStatus();
168 // In this method we need to be aware of the special case where
169 // pos + 1 == limit. This indicates that a '\r' was the last char
170 // in the buffer during a readLine. We'll want to maintain that
171 // condition after we shift things around and if a larger buffer is
172 // needed to track readLimit, we'll have to make it one element
173 // larger to ensure we don't invalidate the mark too early, if the
174 // char following the '\r' is NOT a '\n'. This is ok because, per
175 // the spec, we are not required to invalidate when passing readLimit.
177 // Note that if 'pos > limit', then doing 'limit -= pos' will cause
178 // limit to be negative. This is the only way limit will be < 0.
180 if (pos + readLimit > limit)
182 char[] old_buffer = buffer;
183 int extraBuffSpace = 0;
184 if (pos > limit)
185 extraBuffSpace = 1;
186 if (readLimit + extraBuffSpace > limit)
187 buffer = new char[readLimit + extraBuffSpace];
188 limit -= pos;
189 if (limit >= 0)
191 System.arraycopy(old_buffer, pos, buffer, 0, limit);
192 pos = 0;
196 if (limit < 0)
198 // Maintain the relationship of 'pos > limit'.
199 pos = 1;
200 limit = markPos = 0;
202 else
203 markPos = pos;
204 // Now pos + readLimit <= buffer.length. thus if we need to read
205 // beyond buffer.length, then we are allowed to invalidate markPos.
210 * Reset the stream to the point where the <code>mark()</code> method
211 * was called. Any chars that were read after the mark point was set will
212 * be re-read during subsequent reads.
213 * <p>
214 * This method will throw an IOException if the number of chars read from
215 * the stream since the call to <code>mark()</code> exceeds the mark limit
216 * passed when establishing the mark.
218 * @exception IOException If an error occurs;
220 public void reset() throws IOException
222 synchronized (lock)
224 checkStatus();
225 if (markPos < 0)
226 throw new IOException("mark never set or invalidated");
228 // Need to handle the extremely unlikely case where a readLine was
229 // done with a '\r' as the last char in the buffer; which was then
230 // immediately followed by a mark and a reset with NO intervening
231 // read of any sort. In that case, setting pos to markPos would
232 // lose that info and a subsequent read would thus not skip a '\n'
233 // (if one exists). The value of limit in this rare case is zero.
234 // We can assume that if limit is zero for other reasons, then
235 // pos is already set to zero and doesn't need to be readjusted.
236 if (limit > 0)
237 pos = markPos;
242 * This method determines whether or not a stream is ready to be read. If
243 * This method returns <code>false</code> then this stream could (but is
244 * not guaranteed to) block on the next read attempt.
246 * @return <code>true</code> if this stream is ready to be read, <code>false</code> otherwise
248 * @exception IOException If an error occurs
250 public boolean ready() throws IOException
252 synchronized (lock)
254 checkStatus();
255 return pos < limit || in.ready();
260 * This method read chars from a stream and stores them into a caller
261 * supplied buffer. It starts storing the data at index <code>offset</code> into
262 * the buffer and attempts to read <code>len</code> chars. This method can
263 * return before reading the number of chars requested. The actual number
264 * of chars read is returned as an int. A -1 is returned to indicate the
265 * end of the stream.
266 * <p>
267 * This method will block until some data can be read.
269 * @param buf The array into which the chars read should be stored
270 * @param offset The offset into the array to start storing chars
271 * @param count The requested number of chars to read
273 * @return The actual number of chars read, or -1 if end of stream.
275 * @exception IOException If an error occurs.
277 public int read(char[] buf, int offset, int count) throws IOException
279 synchronized (lock)
281 checkStatus();
282 // Once again, we need to handle the special case of a readLine
283 // that has a '\r' at the end of the buffer. In this case, we'll
284 // need to skip a '\n' if it is the next char to be read.
285 // This special case is indicated by 'pos > limit'.
286 boolean retAtEndOfBuffer = false;
288 int avail = limit - pos;
289 if (count > avail)
291 if (avail > 0)
292 count = avail;
293 else // pos >= limit
295 if (limit == buffer.length)
296 markPos = -1; // read too far - invalidate the mark.
297 if (pos > limit)
299 // Set a boolean and make pos == limit to simplify things.
300 retAtEndOfBuffer = true;
301 --pos;
303 if (markPos < 0)
305 // Optimization: can read directly into buf.
306 if (count >= buffer.length && !retAtEndOfBuffer)
307 return in.read(buf, offset, count);
308 pos = limit = 0;
310 avail = in.read(buffer, limit, buffer.length - limit);
311 if (retAtEndOfBuffer && avail > 0 && buffer[limit] == '\n')
313 --avail;
314 limit++;
316 if (avail < count)
318 if (avail <= 0)
319 return avail;
320 count = avail;
322 limit += avail;
325 System.arraycopy(buffer, pos, buf, offset, count);
326 pos += count;
327 return count;
331 /* Read more data into the buffer. Update pos and limit appropriately.
332 Assumes pos==limit initially. May invalidate the mark if read too much.
333 Return number of chars read (never 0), or -1 on eof. */
334 private int fill() throws IOException
336 checkStatus();
337 // Handle the special case of a readLine that has a '\r' at the end of
338 // the buffer. In this case, we'll need to skip a '\n' if it is the
339 // next char to be read. This special case is indicated by 'pos > limit'.
340 boolean retAtEndOfBuffer = false;
341 if (pos > limit)
343 retAtEndOfBuffer = true;
344 --pos;
347 if (markPos >= 0 && limit == buffer.length)
348 markPos = -1;
349 if (markPos < 0)
350 pos = limit = 0;
351 int count = in.read(buffer, limit, buffer.length - limit);
352 if (count > 0)
353 limit += count;
355 if (retAtEndOfBuffer && buffer[pos] == '\n')
357 --count;
358 // If the mark was set to the location of the \n, then we
359 // must change it to fully pretend that the \n does not
360 // exist.
361 if (markPos == pos)
362 ++markPos;
363 ++pos;
366 return count;
369 public int read() throws IOException
371 synchronized (lock)
373 checkStatus();
374 if (pos >= limit && fill () <= 0)
375 return -1;
376 return buffer[pos++];
380 /* Return the end of the line starting at this.pos and ending at limit.
381 * The index returns is *before* any line terminators, or limit
382 * if no line terminators were found.
384 private int lineEnd(int limit)
386 int i = pos;
387 for (; i < limit; i++)
389 char ch = buffer[i];
390 if (ch == '\n' || ch == '\r')
391 break;
393 return i;
397 * This method reads a single line of text from the input stream, returning
398 * it as a <code>String</code>. A line is terminated by "\n", a "\r", or
399 * an "\r\n" sequence. The system dependent line separator is not used.
400 * The line termination characters are not returned in the resulting
401 * <code>String</code>.
403 * @return The line of text read, or <code>null</code> if end of stream.
405 * @exception IOException If an error occurs
407 public String readLine() throws IOException
409 checkStatus();
410 // Handle the special case where a previous readLine (with no intervening
411 // reads/skips) had a '\r' at the end of the buffer.
412 // In this case, we'll need to skip a '\n' if it's the next char to be read.
413 // This special case is indicated by 'pos > limit'.
414 if (pos > limit)
416 int ch = read();
417 if (ch < 0)
418 return null;
419 if (ch != '\n')
420 --pos;
422 int i = lineEnd(limit);
423 if (i < limit)
425 String str = new String(buffer, pos, i - pos);
426 pos = i + 1;
427 // If the last char in the buffer is a '\r', we must remember
428 // to check if the next char to be read after the buffer is refilled
429 // is a '\n'. If so, skip it. To indicate this condition, we set pos
430 // to be limit + 1, which normally is never possible.
431 if (buffer[i] == '\r')
432 if (pos == limit || buffer[pos] == '\n')
433 pos++;
434 return str;
436 StringBuffer sbuf = new StringBuffer(200);
437 sbuf.append(buffer, pos, i - pos);
438 pos = i;
439 // We only want to return null when no characters were read before
440 // EOF. So we must keep track of this separately. Otherwise we
441 // would treat an empty `sbuf' as an EOF condition, which is wrong
442 // when there is just a newline.
443 boolean eof = false;
444 for (;;)
446 int ch = read();
447 if (ch < 0)
449 eof = true;
450 break;
452 if (ch == '\n' || ch == '\r')
454 // Check here if a '\r' was the last char in the buffer; if so,
455 // mark it as in the comment above to indicate future reads
456 // should skip a newline that is the next char read after
457 // refilling the buffer.
458 if (ch == '\r')
459 if (pos == limit || buffer[pos] == '\n')
460 pos++;
461 break;
463 i = lineEnd(limit);
464 sbuf.append(buffer, pos - 1, i - (pos - 1));
465 pos = i;
467 return (sbuf.length() == 0 && eof) ? null : sbuf.toString();
471 * This method skips the specified number of chars in the stream. It
472 * returns the actual number of chars skipped, which may be less than the
473 * requested amount.
474 * <p>
475 * This method first discards chars in the buffer, then calls the
476 * <code>skip</code> method on the underlying stream to skip the remaining chars.
478 * @param num_chars The requested number of chars to skip
480 * @return The actual number of chars skipped.
482 * @exception IOException If an error occurs
484 public long skip(long count) throws IOException
486 synchronized (lock)
488 checkStatus();
489 if (count <= 0)
490 return 0;
491 // Yet again, we need to handle the special case of a readLine
492 // that has a '\r' at the end of the buffer. In this case, we need
493 // to ignore a '\n' if it is the next char to be read.
494 // This special case is indicated by 'pos > limit' (i.e. avail < 0).
495 // To simplify things, if we're dealing with the special case for
496 // readLine, just read the next char (since the fill method will
497 // skip the '\n' for us). By doing this, we'll have to back up pos.
498 // That's easier than trying to keep track of whether we've skipped
499 // one element or not.
500 int ch;
501 if (pos > limit)
502 if ((ch = read()) < 0)
503 return 0;
504 else
505 --pos;
507 int avail = limit - pos;
509 if (count < avail)
511 pos += count;
512 return count;
515 pos = limit;
516 long todo = count - avail;
517 if (todo > buffer.length)
519 markPos = -1;
520 todo -= in.skip(todo);
522 else
524 while (todo > 0)
526 avail = fill();
527 if (avail <= 0)
528 break;
529 if (avail > todo)
530 avail = (int) todo;
531 pos += avail;
532 todo -= avail;
535 return count - todo;
539 private void checkStatus() throws IOException
541 if (in == null)
542 throw new IOException("Stream closed");