summaryrefslogtreecommitdiffstats
path: root/simple/simple-common/src/test/java/org/simpleframework/common/buffer/queue/BufferQueue.java
blob: 5f3e97f8dfe5876e0943b413a345194fee10b4ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package org.simpleframework.common.buffer.queue;

import java.io.IOException;
import java.io.InputStream;

import org.simpleframework.common.buffer.ArrayBuffer;
import org.simpleframework.common.buffer.Buffer;

public class BufferQueue implements Buffer {
   
   private final ByteQueue queue;
   private final Buffer buffer;
   
   public BufferQueue(ByteQueue queue) {
      this.buffer = new ArrayBuffer();
      this.queue = queue;
   }

   public InputStream open() throws IOException {
      return new ByteQueueStream(queue);
   }

   public Buffer allocate() throws IOException {     
      return new BufferQueue(queue);
   }

   public String encode() throws IOException {
      return encode("UTF-8");
   }

   public String encode(String charset) throws IOException {
      InputStream source = open();      
      byte[] chunk = new byte[512];      
      int count = 0;
      
      while((count = source.read(chunk)) != -1) {
         buffer.append(chunk, 0, count);
      }
      return buffer.encode(charset);
   }

   public Buffer append(byte[] array) throws IOException {
      if(array.length > 0) {
         queue.write(array);
      }
      return this;
   }

   public Buffer append(byte[] array, int off, int len) throws IOException {
      if(len > 0) {
         queue.write(array, off, len);
      }
      return this;
   }

   public void clear() throws IOException {
      queue.reset();
   }

   public void close() throws IOException {
      queue.close();
   }
   
   public long length() {
      return buffer.length();
   }
}