View Javadoc
1   package org.davidmoten.io.extras.internal;
2   
3   import java.io.IOException;
4   import java.io.OutputStream;
5   import java.nio.ByteBuffer;
6   import java.util.Queue;
7   
8   public final class QueuedOutputStream extends OutputStream {
9   
10      private final Queue<ByteBuffer> queue;
11      private final int[] count;// single element array
12      private boolean closed;
13  
14      QueuedOutputStream(Queue<ByteBuffer> queue, int[] count) {
15          this.queue = queue;
16          this.count = count;
17      }
18  
19      @Override
20      public void write(int b) throws IOException {
21          byte[] bytes = new byte[1];
22          bytes[0] = (byte) b;
23          add(ByteBuffer.wrap(bytes));
24      }
25  
26      @Override
27      public void write(byte[] b) throws IOException {
28          add(ByteBuffer.wrap(b));
29      }
30  
31      @Override
32      public void write(byte[] b, int off, int len) throws IOException {
33          add(ByteBuffer.wrap(b, off, len));
34      }
35  
36      private void add(ByteBuffer bb) throws IOException {
37          if (closed) {
38              throw new IOException("Stream closed");
39          }
40          // must copy the byte buffer because may get reused upstream (this happens with
41          // GzipOutputStream!)
42          count[0] += bb.remaining();
43          queue.offer(Util.copy(bb));
44      }
45  
46      @Override
47      public void flush() throws IOException {
48          // ignore
49      }
50  
51      @Override
52      public void close() throws IOException {
53          closed = true;
54      }
55  
56  }