-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathJZlibEncoder.cs
More file actions
249 lines (213 loc) · 8.72 KB
/
Copy pathJZlibEncoder.cs
File metadata and controls
249 lines (213 loc) · 8.72 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Codecs.Compression
{
using System;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels;
public class JZlibEncoder : ZlibEncoder
{
readonly int wrapperOverhead;
readonly Deflater z = new Deflater();
volatile bool finished;
volatile IChannelHandlerContext ctx;
public JZlibEncoder() : this(6)
{
}
public JZlibEncoder(int compressionLevel) : this(ZlibWrapper.Zlib, compressionLevel)
{
}
public JZlibEncoder(ZlibWrapper wrapper) : this(wrapper, 6)
{
}
public JZlibEncoder(ZlibWrapper wrapper, int compressionLevel) : this(wrapper, compressionLevel, 15, 8)
{
}
/**
* Creates a new zlib encoder with the specified {@code compressionLevel},
* the specified {@code windowBits}, the specified {@code memLevel}, and
* the specified wrapper.
*
* @param compressionLevel
* {@code 1} yields the fastest compression and {@code 9} yields the
* best compression. {@code 0} means no compression. The default
* compression level is {@code 6}.
* @param windowBits
* The base two logarithm of the size of the history buffer. The
* value should be in the range {@code 9} to {@code 15} inclusive.
* Larger values result in better compression at the expense of
* memory usage. The default value is {@code 15}.
* @param memLevel
* How much memory should be allocated for the internal compression
* state. {@code 1} uses minimum memory and {@code 9} uses maximum
* memory. Larger values result in better and faster compression
* at the expense of memory usage. The default value is {@code 8}
*
* @throws CompressionException if failed to initialize zlib
*/
public JZlibEncoder(ZlibWrapper wrapper, int compressionLevel, int windowBits, int memLevel)
{
Contract.Requires(compressionLevel >= 0 && compressionLevel <= 9);
Contract.Requires(windowBits >= 9 && windowBits <= 15);
Contract.Requires(memLevel >= 1 && memLevel <= 9);
int resultCode = this.z.Init(
compressionLevel, windowBits, memLevel,
ZlibUtil.ConvertWrapperType(wrapper));
if (resultCode != JZlib.Z_OK)
{
ZlibUtil.Fail(this.z, "initialization failure", resultCode);
}
this.wrapperOverhead = ZlibUtil.WrapperOverhead(wrapper);
}
public JZlibEncoder(byte[] dictionary) : this(6, dictionary)
{
}
public JZlibEncoder(int compressionLevel, byte[] dictionary) : this(compressionLevel, 15, 8, dictionary)
{
}
public JZlibEncoder(int compressionLevel, int windowBits, int memLevel, byte[] dictionary)
{
Contract.Requires(compressionLevel >= 0 && compressionLevel <= 9);
Contract.Requires(windowBits >= 9 && windowBits <= 15);
Contract.Requires(memLevel >= 1 && memLevel <= 9);
int resultCode = this.z.DeflateInit(
compressionLevel, windowBits, memLevel,
JZlib.W_ZLIB); // Default: ZLIB format
if (resultCode != JZlib.Z_OK)
{
ZlibUtil.Fail(this.z, "initialization failure", resultCode);
}
else
{
resultCode = this.z.DeflateSetDictionary(dictionary, dictionary.Length);
if (resultCode != JZlib.Z_OK)
{
ZlibUtil.Fail(this.z, "failed to set the dictionary", resultCode);
}
}
this.wrapperOverhead = ZlibUtil.WrapperOverhead(ZlibWrapper.Zlib);
}
public override Task CloseAsync() => this.CloseAsync(this.CurrentContext());
public override Task CloseAsync(IChannelHandlerContext context) => this.FinishEncode(context);
IChannelHandlerContext CurrentContext()
{
IChannelHandlerContext context = this.ctx;
if (context == null)
{
throw new InvalidOperationException("not added to a pipeline");
}
return context;
}
public override bool IsClosed => this.finished;
protected override void Encode(IChannelHandlerContext context, IByteBuffer message, IByteBuffer output)
{
if (this.finished)
{
output.WriteBytes(message);
return;
}
int inputLength = message.ReadableBytes;
if (inputLength == 0)
{
return;
}
try
{
// Configure input.
bool inHasArray = message.HasArray;
this.z.avail_in = inputLength;
if (inHasArray)
{
this.z.next_in = message.Array;
this.z.next_in_index = message.ArrayOffset + message.ReaderIndex;
}
else
{
var array = new byte[inputLength];
message.GetBytes(message.ReaderIndex, array);
this.z.next_in = array;
this.z.next_in_index = 0;
}
int oldNextInIndex = this.z.next_in_index;
// Configure output.
int maxOutputLength = (int)Math.Ceiling(inputLength * 1.001) + 12 + this.wrapperOverhead;
output.EnsureWritable(maxOutputLength);
this.z.avail_out = maxOutputLength;
this.z.next_out = output.Array;
this.z.next_out_index = output.ArrayOffset + output.WriterIndex;
int oldNextOutIndex = this.z.next_out_index;
int resultCode;
try
{
resultCode = this.z.Deflate(JZlib.Z_SYNC_FLUSH);
}
finally
{
message.SkipBytes(this.z.next_in_index - oldNextInIndex);
}
if (resultCode != JZlib.Z_OK)
{
ZlibUtil.Fail(this.z, "compression failure", resultCode);
}
int outputLength = this.z.next_out_index - oldNextOutIndex;
if (outputLength > 0)
{
output.SetWriterIndex(output.WriterIndex + outputLength);
}
}
finally
{
this.z.next_in = null;
this.z.next_out = null;
}
}
Task FinishEncode(IChannelHandlerContext context)
{
if (this.finished)
{
return TaskEx.Completed;
}
this.finished = true;
IByteBuffer footer;
try
{
// Configure input.
this.z.next_in = ArrayExtensions.ZeroBytes;
this.z.next_in_index = 0;
this.z.avail_in = 0;
// Configure output.
var output = new byte[32]; // room for ADLER32 + ZLIB / CRC32 + GZIP header
this.z.next_out = output;
this.z.next_out_index = 0;
this.z.avail_out = output.Length;
// Write the ADLER32 checksum(stream footer).
int resultCode = this.z.Deflate(JZlib.Z_FINISH);
if (resultCode != JZlib.Z_OK && resultCode != JZlib.Z_STREAM_END)
{
context.FireExceptionCaught(
new CompressionException($"Compression failure ({resultCode}) {this.z.msg}"));
return context.CloseAsync();
}
else if (this.z.next_out_index != 0)
{
footer = Unpooled.WrappedBuffer(output, 0, this.z.next_out_index);
}
else
{
footer = Unpooled.Empty;
}
}
finally
{
this.z.DeflateEnd();
this.z.next_in = null;
this.z.next_out = null;
}
return context.WriteAndFlushAsync(footer).CloseOnComplete(context);
}
public override void HandlerAdded(IChannelHandlerContext context) => this.ctx = context;
}
}