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<Chunk> 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 addChunk(byte buf[], int offset, int length)
40 {
41 if (this.length + length > maxSize)
42 {
43 throw new MessageTooLargeException("Frame is too large");
44 }
45 chunks.add(new Chunk(buf, offset, length));
46 this.length += length;
47 }
48
49 public int getLength()
50 {
51 return length;
52 }
53
54 public void transferTo(ByteBuffer buffer)
55 {
56 if (buffer.remaining() < length)
57 throw new IllegalArgumentException();
58 int position = buffer.position();
59 for (Chunk chunk : chunks)
60 {
61 buffer.put(chunk.buffer, chunk.offset, chunk.length);
62 }
63 BufferUtil.flipToFlush(buffer, position);
64 }
65
66 private static class Chunk
67 {
68 private final byte[] buffer;
69 private final int offset;
70 private final int length;
71
72 private Chunk(byte[] buffer, int offset, int length)
73 {
74 this.buffer = buffer;
75 this.offset = offset;
76 this.length = length;
77 }
78 }
79 }