mp3decoder compiled by our research compiler produces the same output that I get...
[IRC.git] / Robust / src / ClassLibrary / SSJava / 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 @LATTICE("BUF<C,IN<T")
63 @METHODDEFAULT("D<IN,D<C,THISLOC=D")
64 public class BufferedInputStream extends FilterInputStream {
65
66   /**
67    * This is the default buffer size
68    */
69   private static final int DEFAULT_BUFFER_SIZE = 2048; // by default, it is TOP
70
71   /**
72    * The buffer used for storing data from the underlying stream.
73    */
74   @LOC("BUF")
75   protected byte[] buf;
76
77   /**
78    * The number of valid bytes currently in the buffer. It is also the index of
79    * the buffer position one byte past the end of the valid data.
80    */
81   @LOC("C")
82   protected int count;
83
84   /**
85    * The index of the next character that will by read from the buffer. When
86    * <code>pos == count</code>, the buffer is empty.
87    */
88   @LOC("C")
89   protected int pos;
90
91   /**
92    * The value of <code>pos</code> when the <code>mark()</code> method was
93    * called. This is set to -1 if there is no mark set.
94    */
95   @LOC("C")
96   protected int markpos = -1;
97
98   /**
99    * This is the maximum number of bytes than can be read after a call to
100    * <code>mark()</code> before the mark can be discarded. After this may bytes
101    * are read, the <code>reset()</code> method may not be called successfully.
102    */
103   protected int marklimit;
104
105   /**
106    * This is the initial buffer size. When the buffer is grown because of
107    * marking requirements, it will be grown by bufferSize increments. The
108    * underlying stream will be read in chunks of bufferSize.
109    */
110   private final int bufferSize;
111
112   /**
113    * This method initializes a new <code>BufferedInputStream</code> that will
114    * read from the specified subordinate stream with a default buffer size of
115    * 2048 bytes
116    * 
117    * @param in
118    *          The subordinate stream to read from
119    */
120   public BufferedInputStream(InputStream in) {
121     this(in, DEFAULT_BUFFER_SIZE);
122   }
123
124   /**
125    * This method initializes a new <code>BufferedInputStream</code> that will
126    * read from the specified subordinate stream with a buffer size that is
127    * specified by the caller.
128    * 
129    * @param in
130    *          The subordinate stream to read from
131    * @param size
132    *          The buffer size to use
133    * 
134    * @exception IllegalArgumentException
135    *              when size is smaller then 1
136    */
137   public BufferedInputStream(InputStream in, int size) {
138     super(in);
139     if (size <= 0)
140       throw new IllegalArgumentException();
141     buf = new byte[size];
142     // initialize pos & count to bufferSize, to prevent refill from
143     // allocating a new buffer (if the caller starts out by calling mark()).
144     pos = count = bufferSize = size;
145   }
146
147   /**
148    * This method returns the number of bytes that can be read from this stream
149    * before a read can block. A return of 0 indicates that blocking might (or
150    * might not) occur on the very next read attempt.
151    * <p>
152    * The number of available bytes will be the number of read ahead bytes stored
153    * in the internal buffer plus the number of available bytes in the underlying
154    * stream.
155    * 
156    * @return The number of bytes that can be read before blocking could occur
157    * 
158    * @exception IOException
159    *              If an error occurs
160    */
161   public synchronized int available() throws IOException {
162     return count - pos + super.available();
163   }
164
165   /**
166    * This method closes the underlying input stream and frees any resources
167    * associated with it. Sets <code>buf</code> to <code>null</code>.
168    * 
169    * @exception IOException
170    *              If an error occurs.
171    */
172   public void close() throws IOException {
173     // Free up the array memory.
174     buf = null;
175     pos = count = 0;
176     markpos = -1;
177     super.close();
178   }
179
180   /**
181    * This method marks a position in the input to which the stream can be
182    * "reset" by calling the <code>reset()</code> method. The parameter
183    * <code>readlimit</code> is the number of bytes that can be read from the
184    * stream after setting the mark before the mark becomes invalid. For example,
185    * if <code>mark()</code> is called with a read limit of 10, then when 11
186    * bytes of data are read from the stream before the <code>reset()</code>
187    * method is called, then the mark is invalid and the stream object instance
188    * is not required to remember the mark.
189    * <p>
190    * Note that the number of bytes that can be remembered by this method can be
191    * greater than the size of the internal read buffer. It is also not dependent
192    * on the subordinate stream supporting mark/reset functionality.
193    * 
194    * @param readlimit
195    *          The number of bytes that can be read before the mark becomes
196    *          invalid
197    */
198   public synchronized void mark(@LOC("IN") int readlimit) {
199     marklimit = readlimit;
200     markpos = pos;
201   }
202
203   /**
204    * This method returns <code>true</code> to indicate that this class supports
205    * mark/reset functionality.
206    * 
207    * @return <code>true</code> to indicate that mark/reset functionality is
208    *         supported
209    * 
210    */
211   public boolean markSupported() {
212     return true;
213   }
214
215   /**
216    * This method reads an unsigned byte from the input stream and returns it as
217    * an int in the range of 0-255. This method also will return -1 if the end of
218    * the stream has been reached.
219    * <p>
220    * This method will block until the byte can be read.
221    * 
222    * @return The byte read or -1 if end of stream
223    * 
224    * @exception IOException
225    *              If an error occurs
226    */
227   public synchronized int read() throws IOException {
228     if (pos >= count && !refill())
229       return -1; // EOF
230
231     return buf[pos++] & 0xFF;
232   }
233
234   /**
235    * This method reads bytes from a stream and stores them into a caller
236    * supplied buffer. It starts storing the data at index <code>off</code> into
237    * the buffer and attempts to read <code>len</code> bytes. This method can
238    * return before reading the number of bytes requested, but it will try to
239    * read the requested number of bytes by repeatedly calling the underlying
240    * stream as long as available() for this stream continues to return a
241    * non-zero value (or until the requested number of bytes have been read). The
242    * actual number of bytes read is returned as an int. A -1 is returned to
243    * indicate the end of the stream.
244    * <p>
245    * This method will block until some data can be read.
246    * 
247    * @param b
248    *          The array into which the bytes read should be stored
249    * @param off
250    *          The offset into the array to start storing bytes
251    * @param len
252    *          The requested number of bytes to read
253    * 
254    * @return The actual number of bytes read, or -1 if end of stream.
255    * 
256    * @exception IOException
257    *              If an error occurs.
258    * @exception IndexOutOfBoundsException
259    *              when <code>off</code> or <code>len</code> are negative, or
260    *              when <code>off + len</code> is larger then the size of
261    *              <code>b</code>,
262    */
263   public synchronized int read(byte[] b, int off, int len) throws IOException {
264     if (off < 0 || len < 0 || b.length - off < len)
265 //      throw new IndexOutOfBoundsException();
266       return -1;
267
268     if (len == 0)
269       return 0;
270
271     if (pos >= count && !refill())
272       return -1; // No bytes were read before EOF.
273
274     int totalBytesRead = Math.min(count - pos, len);
275     System.arraycopy(buf, pos, b, off, totalBytesRead);
276     pos += totalBytesRead;
277     off += totalBytesRead;
278     len -= totalBytesRead;
279
280     while (len > 0 && super.available() > 0 && refill()) {
281       int remain = Math.min(count - pos, len);
282       System.arraycopy(buf, pos, b, off, remain);
283       pos += remain;
284       off += remain;
285       len -= remain;
286       totalBytesRead += remain;
287     }
288
289     return totalBytesRead;
290   }
291
292   /**
293    * This method resets a stream to the point where the <code>mark()</code>
294    * method was called. Any bytes that were read after the mark point was set
295    * will be re-read during subsequent reads.
296    * <p>
297    * This method will throw an IOException if the number of bytes read from the
298    * stream since the call to <code>mark()</code> exceeds the mark limit passed
299    * when establishing the mark.
300    * 
301    * @exception IOException
302    *              If <code>mark()</code> was never called or more then
303    *              <code>marklimit</code> bytes were read since the last call to
304    *              <code>mark()</code>
305    */
306   public synchronized void reset() throws IOException {
307     if (markpos == -1)
308       throw new IOException(buf == null ? "Stream closed." : "Invalid mark.");
309
310     pos = markpos;
311   }
312
313   /**
314    * This method skips the specified number of bytes in the stream. It returns
315    * the actual number of bytes skipped, which may be less than the requested
316    * amount.
317    * 
318    * @param n
319    *          The requested number of bytes to skip
320    * 
321    * @return The actual number of bytes skipped.
322    * 
323    * @exception IOException
324    *              If an error occurs
325    */
326   public synchronized long skip(long n) throws IOException {
327     if (buf == null)
328       throw new IOException("Stream closed.");
329
330     final long origN = n;
331
332     while (n > 0L) {
333       if (pos >= count && !refill())
334         break;
335
336       int numread = (int) Math.min((long) (count - pos), n);
337       pos += numread;
338       n -= numread;
339     }
340
341     return origN - n;
342   }
343
344   /**
345    * Called to refill the buffer (when count is equal to pos).
346    * 
347    * @return <code>true</code> when at least one additional byte was read into
348    *         <code>buf</code>, <code>false</code> otherwise (at EOF).
349    */
350   private boolean refill() throws IOException {
351     if (buf == null)
352       throw new IOException("Stream closed.");
353
354     if (markpos == -1 || count - markpos >= marklimit) {
355       markpos = -1;
356       pos = count = 0;
357     } else {
358       byte[] newbuf = buf;
359       if (markpos < bufferSize) {
360         newbuf = new byte[count - markpos + bufferSize];
361       }
362       System.arraycopy(buf, markpos, newbuf, 0, count - markpos);
363       buf = newbuf;
364       count -= markpos;
365       pos -= markpos;
366       markpos = 0;
367     }
368
369     int numread = super.read(buf, count, bufferSize);
370
371     if (numread <= 0) // EOF
372       return false;
373
374     count += numread;
375     return true;
376   }
377 }