reformat benchmark source codes to meet the requirements of the annotation generation.
[IRC.git] / Robust / src / ClassLibrary / SSJavaInfer / BufferedInputStream.java
1 /* BufferedInputStream.java -- An input stream that implements buffering
2    Copyright (C) 1998, 1999, 2001, 2005  Free Software Foundation, Inc.
3
4 This file is part of GNU Classpath.
5
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.
10
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.
15
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., 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301 USA.
20
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.
25
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. */
37
38 /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
39  * "The Java Language Specification", ISBN 0-201-63451-1
40  * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
41  * Status:  Believed complete and correct.
42  */
43
44 /**
45  * This subclass of <code>FilterInputStream</code> buffers input from an
46  * underlying implementation to provide a possibly more efficient read
47  * mechanism. It maintains the buffer and buffer state in instance variables
48  * that are available to subclasses. The default buffer size of 2048 bytes can
49  * be overridden by the creator of the stream.
50  * <p>
51  * This class also implements mark/reset functionality. It is capable of
52  * remembering any number of input bytes, to the limits of system memory or the
53  * size of <code>Integer.MAX_VALUE</code>
54  * <p>
55  * Please note that this class does not properly handle character encodings.
56  * Consider using the <code>BufferedReader</code> class which does.
57  * 
58  * @author Aaron M. Renn (arenn@urbanophile.com)
59  * @author Warren Levy (warrenl@cygnus.com)
60  * @author Jeroen Frijters (jeroen@frijters.net)
61  */
62
63 public class BufferedInputStream extends FilterInputStream {
64
65   /**
66    * This is the default buffer size
67    */
68   private static final int DEFAULT_BUFFER_SIZE = 2048; // by default, it is TOP
69
70   /**
71    * The buffer used for storing data from the underlying stream.
72    */
73
74   protected byte[] buf;
75
76   /**
77    * The number of valid bytes currently in the buffer. It is also the index of
78    * the buffer position one byte past the end of the valid data.
79    */
80
81   protected int count;
82
83   /**
84    * The index of the next character that will by read from the buffer. When
85    * <code>pos == count</code>, the buffer is empty.
86    */
87
88   protected int pos;
89
90   /**
91    * The value of <code>pos</code> when the <code>mark()</code> method was
92    * called. This is set to -1 if there is no mark set.
93    */
94
95   protected int markpos = -1;
96
97   /**
98    * This is the maximum number of bytes than can be read after a call to
99    * <code>mark()</code> before the mark can be discarded. After this may bytes
100    * are read, the <code>reset()</code> method may not be called successfully.
101    */
102   protected int marklimit;
103
104   /**
105    * This is the initial buffer size. When the buffer is grown because of
106    * marking requirements, it will be grown by bufferSize increments. The
107    * underlying stream will be read in chunks of bufferSize.
108    */
109   private final int bufferSize;
110
111   /**
112    * This method initializes a new <code>BufferedInputStream</code> that will
113    * read from the specified subordinate stream with a default buffer size of
114    * 2048 bytes
115    * 
116    * @param in
117    *          The subordinate stream to read from
118    */
119   public BufferedInputStream(InputStream in) {
120     this(in, DEFAULT_BUFFER_SIZE);
121   }
122
123   /**
124    * This method initializes a new <code>BufferedInputStream</code> that will
125    * read from the specified subordinate stream with a buffer size that is
126    * specified by the caller.
127    * 
128    * @param in
129    *          The subordinate stream to read from
130    * @param size
131    *          The buffer size to use
132    * 
133    * @exception IllegalArgumentException
134    *              when size is smaller then 1
135    */
136   public BufferedInputStream(InputStream in, int size) {
137     super(in);
138     if (size <= 0)
139       throw new IllegalArgumentException();
140     buf = new byte[size];
141     // initialize pos & count to bufferSize, to prevent refill from
142     // allocating a new buffer (if the caller starts out by calling mark()).
143     pos = count = bufferSize = size;
144   }
145
146   /**
147    * This method returns the number of bytes that can be read from this stream
148    * before a read can block. A return of 0 indicates that blocking might (or
149    * might not) occur on the very next read attempt.
150    * <p>
151    * The number of available bytes will be the number of read ahead bytes stored
152    * in the internal buffer plus the number of available bytes in the underlying
153    * stream.
154    * 
155    * @return The number of bytes that can be read before blocking could occur
156    * 
157    * @exception IOException
158    *              If an error occurs
159    */
160   public synchronized int available() throws IOException {
161     return count - pos + super.available();
162   }
163
164   /**
165    * This method closes the underlying input stream and frees any resources
166    * associated with it. Sets <code>buf</code> to <code>null</code>.
167    * 
168    * @exception IOException
169    *              If an error occurs.
170    */
171   public void close() throws IOException {
172     // Free up the array memory.
173     buf = null;
174     pos = count = 0;
175     markpos = -1;
176     super.close();
177   }
178
179   /**
180    * This method marks a position in the input to which the stream can be
181    * "reset" by calling the <code>reset()</code> method. The parameter
182    * <code>readlimit</code> is the number of bytes that can be read from the
183    * stream after setting the mark before the mark becomes invalid. For example,
184    * if <code>mark()</code> is called with a read limit of 10, then when 11
185    * bytes of data are read from the stream before the <code>reset()</code>
186    * method is called, then the mark is invalid and the stream object instance
187    * is not required to remember the mark.
188    * <p>
189    * Note that the number of bytes that can be remembered by this method can be
190    * greater than the size of the internal read buffer. It is also not dependent
191    * on the subordinate stream supporting mark/reset functionality.
192    * 
193    * @param readlimit
194    *          The number of bytes that can be read before the mark becomes
195    *          invalid
196    */
197   public synchronized void mark(int readlimit) {
198     marklimit = readlimit;
199     markpos = pos;
200   }
201
202   /**
203    * This method returns <code>true</code> to indicate that this class supports
204    * mark/reset functionality.
205    * 
206    * @return <code>true</code> to indicate that mark/reset functionality is
207    *         supported
208    * 
209    */
210   public boolean markSupported() {
211     return true;
212   }
213
214   /**
215    * This method reads an unsigned byte from the input stream and returns it as
216    * an int in the range of 0-255. This method also will return -1 if the end of
217    * the stream has been reached.
218    * <p>
219    * This method will block until the byte can be read.
220    * 
221    * @return The byte read or -1 if end of stream
222    * 
223    * @exception IOException
224    *              If an error occurs
225    */
226   public synchronized int read() throws IOException {
227     if (pos >= count && !refill())
228       return -1; // EOF
229
230     return buf[pos++] & 0xFF;
231   }
232
233   /**
234    * This method reads bytes from a stream and stores them into a caller
235    * supplied buffer. It starts storing the data at index <code>off</code> into
236    * the buffer and attempts to read <code>len</code> bytes. This method can
237    * return before reading the number of bytes requested, but it will try to
238    * read the requested number of bytes by repeatedly calling the underlying
239    * stream as long as available() for this stream continues to return a
240    * non-zero value (or until the requested number of bytes have been read). The
241    * actual number of bytes read is returned as an int. A -1 is returned to
242    * indicate the end of the stream.
243    * <p>
244    * This method will block until some data can be read.
245    * 
246    * @param b
247    *          The array into which the bytes read should be stored
248    * @param off
249    *          The offset into the array to start storing bytes
250    * @param len
251    *          The requested number of bytes to read
252    * 
253    * @return The actual number of bytes read, or -1 if end of stream.
254    * 
255    * @exception IOException
256    *              If an error occurs.
257    * @exception IndexOutOfBoundsException
258    *              when <code>off</code> or <code>len</code> are negative, or
259    *              when <code>off + len</code> is larger then the size of
260    *              <code>b</code>,
261    */
262   public synchronized int read(byte[] b, int off, int len) throws IOException {
263     if (off < 0 || len < 0 || b.length - off < len)
264       // throw new IndexOutOfBoundsException();
265       return -1;
266
267     if (len == 0)
268       return 0;
269
270     if (pos >= count && !refill())
271       return -1; // No bytes were read before EOF.
272
273     int totalBytesRead = Math.min(count - pos, len);
274     System.arraycopy(buf, pos, b, off, totalBytesRead);
275     pos += totalBytesRead;
276     off += totalBytesRead;
277     len -= totalBytesRead;
278
279     while (len > 0 && super.available() > 0 && refill()) {
280       int remain = Math.min(count - pos, len);
281       System.arraycopy(buf, pos, b, off, remain);
282       pos += remain;
283       off += remain;
284       len -= remain;
285       totalBytesRead += remain;
286     }
287
288     return totalBytesRead;
289   }
290
291   /**
292    * This method resets a stream to the point where the <code>mark()</code>
293    * method was called. Any bytes that were read after the mark point was set
294    * will be re-read during subsequent reads.
295    * <p>
296    * This method will throw an IOException if the number of bytes read from the
297    * stream since the call to <code>mark()</code> exceeds the mark limit passed
298    * when establishing the mark.
299    * 
300    * @exception IOException
301    *              If <code>mark()</code> was never called or more then
302    *              <code>marklimit</code> bytes were read since the last call to
303    *              <code>mark()</code>
304    */
305   public synchronized void reset() throws IOException {
306     if (markpos == -1)
307       throw new IOException(buf == null ? "Stream closed." : "Invalid mark.");
308
309     pos = markpos;
310   }
311
312   /**
313    * This method skips the specified number of bytes in the stream. It returns
314    * the actual number of bytes skipped, which may be less than the requested
315    * amount.
316    * 
317    * @param n
318    *          The requested number of bytes to skip
319    * 
320    * @return The actual number of bytes skipped.
321    * 
322    * @exception IOException
323    *              If an error occurs
324    */
325   public synchronized long skip(long n) throws IOException {
326     if (buf == null)
327       throw new IOException("Stream closed.");
328
329     final long origN = n;
330
331     while (n > 0L) {
332       if (pos >= count && !refill())
333         break;
334
335       int numread = (int) Math.min((long) (count - pos), n);
336       pos += numread;
337       n -= numread;
338     }
339
340     return origN - n;
341   }
342
343   /**
344    * Called to refill the buffer (when count is equal to pos).
345    * 
346    * @return <code>true</code> when at least one additional byte was read into
347    *         <code>buf</code>, <code>false</code> otherwise (at EOF).
348    */
349   private boolean refill() throws IOException {
350     if (buf == null)
351       throw new IOException("Stream closed.");
352
353     if (markpos == -1 || count - markpos >= marklimit) {
354       markpos = -1;
355       pos = count = 0;
356     } else {
357       byte[] newbuf = buf;
358       if (markpos < bufferSize) {
359         newbuf = new byte[count - markpos + bufferSize];
360       }
361       System.arraycopy(buf, markpos, newbuf, 0, count - markpos);
362       buf = newbuf;
363       count -= markpos;
364       pos -= markpos;
365       markpos = 0;
366     }
367
368     int numread = super.read(buf, count, bufferSize);
369
370     if (numread <= 0) // EOF
371       return false;
372
373     count += numread;
374     return true;
375   }
376 }