1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.compression;
17
18 import com.github.luben.zstd.ZstdInputStreamNoFinalizer;
19 import io.netty.buffer.ByteBuf;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.handler.codec.ByteToMessageDecoder;
22 import io.netty.util.internal.ObjectUtil;
23
24 import java.io.Closeable;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.util.List;
28
29
30
31
32
33 public final class ZstdDecoder extends ByteToMessageDecoder {
34
35 {
36 try {
37 Zstd.ensureAvailability();
38 } catch (Throwable throwable) {
39 throw new ExceptionInInitializerError(throwable);
40 }
41 }
42
43 private static final int DEFAULT_MAX_FORWARD_BYTES = CompressionUtil.DEFAULT_MAX_FORWARD_BYTES;
44
45
46 static final int DEFAULT_OUTPUT_BUFFER_SIZE = 64 * 1024;
47
48
49
50 public static final int DEFAULT_MAXIMUM_ALLOCATION_SIZE = 4 * 1024 * 1024;
51
52
53
54
55 public static final int DEFAULT_MAX_WINDOW_LOG = 27;
56 private static final int MIN_WINDOW_LOG = 10;
57 private static final int MAX_WINDOW_LOG = 31;
58 private final int maxForwardBytes;
59 private final int outputBufferSize;
60 private final int maxWindowLog;
61 private final MutableByteBufInputStream inputStream = new MutableByteBufInputStream();
62 private ZstdInputStreamNoFinalizer zstdIs;
63
64 private boolean needsRead;
65 private State currentState = State.DECOMPRESS_DATA;
66
67
68
69
70 private enum State {
71 DECOMPRESS_DATA,
72 CORRUPTED
73 }
74
75
76
77
78
79
80
81
82
83 public ZstdDecoder() {
84 this(DEFAULT_MAXIMUM_ALLOCATION_SIZE, DEFAULT_MAX_WINDOW_LOG);
85 }
86
87
88
89
90
91
92
93
94
95
96 public ZstdDecoder(int maximumAllocationSize) {
97 this(maximumAllocationSize, DEFAULT_MAX_WINDOW_LOG);
98 }
99
100
101
102
103
104
105
106
107
108
109 public ZstdDecoder(int maximumAllocationSize, int maxWindowLog) {
110 this(maximumAllocationSize, maxWindowLog, DEFAULT_MAX_FORWARD_BYTES);
111 }
112
113
114 ZstdDecoder(int maximumAllocationSize, int maxWindowLog, int defaultMaxForwardBytes) {
115 ObjectUtil.checkPositiveOrZero(maximumAllocationSize, "maximumAllocationSize");
116 this.maxForwardBytes = maximumAllocationSize > 0 ? maximumAllocationSize : defaultMaxForwardBytes;
117 this.outputBufferSize = maxForwardBytes > 0 ? maxForwardBytes : DEFAULT_OUTPUT_BUFFER_SIZE;
118 this.maxWindowLog = ObjectUtil.checkInRange(maxWindowLog, MIN_WINDOW_LOG, MAX_WINDOW_LOG, "maxWindowLog");
119 }
120
121 @Override
122 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
123 needsRead = true;
124 try {
125 if (currentState == State.CORRUPTED) {
126 in.skipBytes(in.readableBytes());
127
128 return;
129 }
130 inputStream.current = in;
131
132 ByteBuf outBuffer = null;
133
134 final int compressedLength = in.readableBytes();
135 try {
136 long uncompressedLength;
137 if (in.isDirect()) {
138 uncompressedLength = com.github.luben.zstd.Zstd.getFrameContentSize(
139 CompressionUtil.safeNioBuffer(in, in.readerIndex(), in.readableBytes()));
140 } else {
141 uncompressedLength = com.github.luben.zstd.Zstd.getFrameContentSize(
142 in.array(), in.readerIndex() + in.arrayOffset(), in.readableBytes());
143 }
144 if (uncompressedLength <= 0) {
145
146
147 uncompressedLength = compressedLength * 2L;
148 }
149
150 int w;
151 do {
152 if (outBuffer == null) {
153
154
155 outBuffer = ctx.alloc().heapBuffer((int) Math.min(outputBufferSize, uncompressedLength));
156 }
157 do {
158 w = outBuffer.writeBytes(zstdIs, outBuffer.writableBytes());
159 } while (w > 0 && outBuffer.isWritable());
160 if (outBuffer.isReadable() &&
161 (!outBuffer.isWritable() || outBuffer.readableBytes() >= maxForwardBytes)) {
162 needsRead = false;
163 ctx.fireChannelRead(outBuffer);
164 outBuffer = null;
165 }
166 } while (w > 0);
167 if (outBuffer != null && outBuffer.isReadable()) {
168 needsRead = false;
169 ctx.fireChannelRead(outBuffer);
170 outBuffer = null;
171 }
172 } finally {
173 if (outBuffer != null) {
174 outBuffer.release();
175 }
176 }
177 } catch (Exception e) {
178 currentState = State.CORRUPTED;
179 throw new DecompressionException(e);
180 } finally {
181 inputStream.current = null;
182 }
183 }
184
185 @Override
186 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
187
188 discardSomeReadBytes();
189
190 if (needsRead && !ctx.channel().config().isAutoRead()) {
191 ctx.read();
192 }
193 ctx.fireChannelReadComplete();
194 }
195
196 @Override
197 public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
198 super.handlerAdded(ctx);
199 zstdIs = new ZstdInputStreamNoFinalizer(inputStream);
200 zstdIs.setContinuous(true);
201
202
203 zstdIs.setLongMax(maxWindowLog);
204 }
205
206 @Override
207 protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
208 try {
209 closeSilently(zstdIs);
210 } finally {
211 super.handlerRemoved0(ctx);
212 }
213 }
214
215 private static void closeSilently(Closeable closeable) {
216 if (closeable != null) {
217 try {
218 closeable.close();
219 } catch (IOException ignore) {
220
221 }
222 }
223 }
224
225 private static final class MutableByteBufInputStream extends InputStream {
226 ByteBuf current;
227
228 @Override
229 public int read() {
230 if (current == null || !current.isReadable()) {
231 return -1;
232 }
233 return current.readByte() & 0xff;
234 }
235
236 @Override
237 public int read(byte[] b, int off, int len) {
238 int available = available();
239 if (available == 0) {
240 return -1;
241 }
242
243 len = Math.min(available, len);
244 current.readBytes(b, off, len);
245 return len;
246 }
247
248 @Override
249 public int available() {
250 return current == null ? 0 : current.readableBytes();
251 }
252 }
253 }