1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.websocket.common.extensions.compress;
20
21 import java.nio.ByteBuffer;
22 import java.util.ArrayList;
23 import java.util.List;
24
25 import org.eclipse.jetty.util.BufferUtil;
26 import org.eclipse.jetty.websocket.api.MessageTooLargeException;
27
28 public class ByteAccumulator
29 {
30 private final List<byte[]> chunks = new ArrayList<>();
31 private final int maxSize;
32 private int length = 0;
33
34 public ByteAccumulator(int maxOverallBufferSize)
35 {
36 this.maxSize = maxOverallBufferSize;
37 }
38
39 public void copyChunk(byte buf[], int offset, int length)
40 {
41 if (this.length + length > maxSize)
42 {
43 throw new MessageTooLargeException("Frame is too large");
44 }
45
46 byte copy[] = new byte[length - offset];
47 System.arraycopy(buf,offset,copy,0,length);
48
49 chunks.add(copy);
50 this.length += length;
51 }
52
53 public int getLength()
54 {
55 return length;
56 }
57
58 public void transferTo(ByteBuffer buffer)
59 {
60 if (buffer.remaining() < length)
61 {
62 throw new IllegalArgumentException(String.format("Not enough space in ByteBuffer remaining [%d] for accumulated buffers length [%d]",
63 buffer.remaining(),length));
64 }
65
66 int position = buffer.position();
67 for (byte[] chunk : chunks)
68 {
69 buffer.put(chunk,0,chunk.length);
70 }
71 BufferUtil.flipToFlush(buffer,position);
72 }
73 }