OSDN Git Service

af375958987088207c1ce2131455fc49b1f77506
[pf3gnuchains/gcc-fork.git] / libjava / java / io / PipedReader.java
1 /* PipedReader.java -- Read portion of piped character streams.
2    Copyright (C) 1998, 1999, 2000, 2001 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., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
20
21 As a special exception, if you link this library with other files to
22 produce an executable, this library does not by itself cause the
23 resulting executable to be covered by the GNU General Public License.
24 This exception does not however invalidate any other reasons why the
25 executable file might be covered by the GNU General Public License. */
26
27 package java.io;
28
29 // NOTE: This implementation is very similar to that of PipedInputStream. 
30 // If you fix a bug in here, chances are you should make a similar change to 
31 // the PipedInputStream code.
32
33 /**
34   * An input stream that reads characters from a piped writer to which it is 
35   * connected. 
36   * <p>
37   * Data is read and written to an internal buffer.  It is highly recommended
38   * that the <code>PipedReader</code> and connected <code>PipedWriter</code>
39   * be part of different threads.  If they are not, there is a possibility
40   * that the read and write operations could deadlock their thread.
41   *
42   * @specnote The JDK implementation appears to have some undocumented 
43   *           functionality where it keeps track of what thread is writing
44   *           to pipe and throws an IOException if that thread susequently
45   *           dies. This behaviour seems dubious and unreliable - we don't
46   *           implement it.
47   *
48   * @author Aaron M. Renn (arenn@urbanophile.com)
49   */
50 public class PipedReader extends Reader
51 {
52   /** PipedWriter to which this is connected. Null only if this 
53     * Reader hasn't been connected yet. */
54   PipedWriter source;
55
56   /** Set to true if close() has been called on this Reader. */
57   boolean closed;
58
59   /**
60     * The size of the internal buffer used for input/output.
61     */
62   static final int PIPE_SIZE = 2048;
63
64   /**
65     * This is the internal circular buffer used for storing chars written
66     * to the pipe and from which chars are read by this stream
67     */
68   char[] buffer = new char[PIPE_SIZE];
69
70   /**
71     * The index into buffer where the next char from the connected
72     * <code>PipedWriter</code> will be written. If this variable is 
73     * equal to <code>out</code>, then the buffer is full. If set to < 0,
74     * the buffer is empty.
75     */
76   int in = -1;
77
78   /**
79     * This index into the buffer where chars will be read from.
80     */
81   int out = 0;
82
83   /** Buffer used to implement single-argument read/receive */
84   char[] read_buf = new char[1];
85
86   /**
87     * Creates a new <code>PipedReader</code> that is not connected to a 
88     * <code>PipedWriter</code>.  It must be connected before chars can 
89     * be read from this stream.
90     */
91   public PipedReader()
92   {
93   }
94
95   /**
96     * This constructor creates a new <code>PipedReader</code> and connects
97     * it to the passed in <code>PipedWriter</code>. The stream is then 
98     * ready for reading.
99     *
100     * @param source The <code>PipedWriter</code> to connect this stream to
101     *
102     * @exception IOException If <code>source</code> is already connected.
103     */
104   public PipedReader(PipedWriter source) throws IOException
105   {
106     connect(source);
107   }
108
109   /**
110     * This method connects this stream to the passed in <code>PipedWriter</code>.
111     * This stream is then ready for reading.  If this stream is already
112     * connected or has been previously closed, then an exception is thrown
113     *
114     * @param src The <code>PipedWriter</code> to connect this stream to
115     *
116     * @exception IOException If this PipedReader or <code>source</code> 
117     *                        has been connected already.
118     */
119   public void connect(PipedWriter source) throws IOException
120   {
121     // The JDK (1.3) does not appear to check for a previously closed 
122     // connection here.
123     
124     if (this.source != null || source.sink != null)
125       throw new IOException ("Already connected");
126     
127     source.sink = this;
128     this.source = source;
129   }
130   
131   /**
132     * This method is used by the connected <code>PipedWriter</code> to
133     * write chars into the buffer.
134     *
135     * @param buf The array containing chars to write to this stream
136     * @param offset The offset into the array to start writing from
137     * @param len The number of chars to write.
138     *
139     * @exception IOException If an error occurs
140     * @specnote This code should be in PipedWriter.write, but we
141     *           put it here in order to support that bizarre recieve(int)
142     *           method.
143     */  
144   void receive(char[] buf, int offset, int len)
145     throws IOException
146   {
147     synchronized (lock)
148     {
149       if (closed)
150         throw new IOException ("Pipe closed");
151
152       int bufpos = offset;
153       int copylen;
154
155       while (len > 0)
156         {
157           try
158             {
159               while (in == out)
160                 {
161                   // The pipe is full. Wake up any readers and wait for them.
162                   lock.notifyAll();
163                   lock.wait();
164                   // The pipe could have been closed while we were waiting.
165                   if (closed)
166                     throw new IOException ("Pipe closed");
167                 }
168             }
169           catch (InterruptedException ix)
170             {
171               throw new InterruptedIOException ();
172             }
173
174           if (in < 0) // The pipe is empty.
175             in = 0;
176
177           // Figure out how many chars from buf can be copied without 
178           // overrunning out or going past the length of the buffer.
179           if (in < out)
180             copylen = Math.min (len, out - in);
181           else
182             copylen = Math.min (len, buffer.length - in);
183
184           // Copy chars until the pipe is filled, wrapping if neccessary.
185           System.arraycopy(buf, bufpos, buffer, in, copylen);
186           len -= copylen;
187           bufpos += copylen;
188           in += copylen;
189           if (in == buffer.length)
190             in = 0;
191         }
192       // Notify readers that new data is in the pipe.
193       lock.notifyAll();
194     }
195   }
196   
197   /**
198     * This method reads chars from the stream into a caller supplied buffer.
199     * It starts storing chars at position <code>offset</code> into the buffer and
200     * reads a maximum of <cod>>len</code> chars.  Note that this method can actually
201     * read fewer than <code>len</code> chars.  The actual number of chars read is
202     * returned.  A -1 is returned to indicated that no chars can be read
203     * because the end of the stream was reached.  If the stream is already
204     * closed, a -1 will again be returned to indicate the end of the stream.
205     * <p>
206     * This method will block if no chars are available to be read.
207     *
208     * @param buf The buffer into which chars will be stored
209     * @param offset The index into the buffer at which to start writing.
210     * @param len The maximum number of chars to read.
211     */
212   public int read() throws IOException
213   {
214     // Method operates by calling the multichar overloaded read method
215     // Note that read_buf is an internal instance variable.  I allocate it
216     // there to avoid constant reallocation overhead for applications that
217     // call this method in a loop at the cost of some unneeded overhead
218     // if this method is never called.
219
220     int r = read(read_buf, 0, 1);
221
222     if (r == -1)
223       return -1;
224     else
225       return read_buf[0];
226   }
227   
228   /**
229     * This method reads characters from the stream into a caller supplied buffer.
230     * It starts storing chars at position <code>offset</code> into the buffer and
231     * reads a maximum of <cod>>len</code> chars.  Note that this method can actually
232     * read fewer than <code>len</code> chars.  The actual number of chars read is
233     * returned.  A -1 is returned to indicated that no chars can be read
234     * because the end of the stream was reached - ie close() was called on the
235     * connected PipedWriter.
236     * <p>
237     * This method will block if no chars are available to be read.
238     *
239     * @param buf The buffer into which chars will be stored
240     * @param offset The index into the buffer at which to start writing.
241     * @param len The maximum number of chars to read.
242     *
243     * @exception IOException If <code>close()/code> was called on this Piped
244     *                        Reader.
245     */  
246   public int read(char[] buf, int offset, int len)
247     throws IOException
248   {
249     synchronized (lock)
250     {
251       if (source == null)
252         throw new IOException ("Not connected");
253       if (closed)
254         throw new IOException ("Pipe closed");
255
256       // If the buffer is empty, wait until there is something in the pipe 
257       // to read.
258       try
259         {
260           while (in < 0)
261             {
262               if (source.closed)
263                 return -1;
264               lock.wait();
265             }
266         }
267       catch (InterruptedException ix)
268         {
269           throw new InterruptedIOException();
270         }
271
272       int total = 0;
273       int copylen;
274
275       while (true)
276         {
277           // Figure out how many chars from the pipe can be copied without 
278           // overrunning in or going past the length of buf.
279           if (out < in)
280             copylen = Math.min (len, in - out);
281           else
282             copylen = Math.min (len, buffer.length - out);
283
284           System.arraycopy (buffer, out, buf, offset, copylen);
285           offset += copylen;
286           len -= copylen;
287           out += copylen;
288           total += copylen;
289
290           if (out == buffer.length)
291             out = 0;
292
293           if (out == in)
294             {
295               // Pipe is now empty.
296               in = -1;
297               out = 0;
298             }
299
300           // If output buffer is filled or the pipe is empty, we're done.
301           if (len == 0 || in == -1)
302             {
303               // Notify any waiting Writer that there is now space
304               // to write.
305               lock.notifyAll();
306               return total;
307             }
308         }
309     }
310   }
311   
312   public boolean ready() throws IOException
313   {
314     // The JDK 1.3 implementation does not appear to check for the closed or 
315     // unconnected stream conditions here.
316     
317     synchronized (lock)
318     {
319       if (in < 0)
320         return false;
321
322       int count;
323       if (out < in)
324         count = in - out;
325       else
326         count = (buffer.length - out) - in;
327
328       return (count > 0);
329     }
330   }
331   
332   /**
333   * This methods closes the stream so that no more data can be read
334   * from it.
335   *
336   * @exception IOException If an error occurs
337   */
338   public void close() throws IOException
339   {
340     synchronized (lock)
341     {
342       closed = true;
343       // Wake any thread which may be in receive() waiting to write data.
344       lock.notifyAll();
345     }
346   }
347 }