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.io.ByteBufferPool;
26 import org.eclipse.jetty.util.BufferUtil;
27 import org.eclipse.jetty.websocket.api.MessageTooLargeException;
28
29 public class ByteAccumulator
30 {
31 private static class Buf
32 {
33 public Buf(byte[] buffer, int offset, int length)
34 {
35 this.buffer = buffer;
36 this.offset = offset;
37 this.length = length;
38 }
39
40 byte[] buffer;
41 int offset;
42 int length;
43 }
44
45 private final int maxSize;
46 private int length = 0;
47 private List<Buf> buffers;
48
49 public ByteAccumulator(int maxOverallBufferSize)
50 {
51 this.maxSize = maxOverallBufferSize;
52 this.buffers = new ArrayList<>();
53 }
54
55 public void addBuffer(byte buf[], int offset, int length)
56 {
57 if (this.length + length > maxSize)
58 {
59 throw new MessageTooLargeException("Frame is too large");
60 }
61 buffers.add(new Buf(buf,offset,length));
62 this.length += length;
63 }
64
65 public int getLength()
66 {
67 return length;
68 }
69
70 public ByteBuffer getByteBuffer(ByteBufferPool pool)
71 {
72 ByteBuffer ret = pool.acquire(length,false);
73 BufferUtil.clearToFill(ret);
74
75 for (Buf buf : buffers)
76 {
77 ret.put(buf.buffer, buf.offset, buf.length);
78 }
79
80 BufferUtil.flipToFlush(ret,0);
81 return ret;
82 }
83 }