OSDN Git Service

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