-
-
Notifications
You must be signed in to change notification settings - Fork 203
/
Lz4DecodeStream.cs
382 lines (321 loc) · 11.8 KB
/
Lz4DecodeStream.cs
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
using System;
using System.IO;
namespace LibCpp2IL;
public class Lz4DecodeStream : Stream
{
private enum DecodePhase
{
ReadToken,
ReadExLiteralLength,
CopyLiteral,
ReadMatch,
ReadExMatchLength,
CopyMatch,
Finish,
}
public Lz4DecodeStream(byte[] buffer, int offset, int length) : this(new MemoryStream(buffer, offset, length), length, false) { }
/// <summary>
/// Whole base stream is compressed data
/// </summary>
/// <param name="baseStream">Stream with compressed data</param>
public Lz4DecodeStream(Stream baseStream, bool leaveOpen = true) : this(baseStream, baseStream.Length, leaveOpen) { }
/// <summary>
/// Part of base stream is compressed data
/// </summary>
/// <param name="baseStream">Stream with compressed data</param>
/// <param name="compressedSize">Amount of comprassed data</param>
public Lz4DecodeStream(Stream baseStream, long compressedSize, bool leaveOpen = true)
{
if (compressedSize <= 0)
{
throw new ArgumentException($"Compressed size {compressedSize} must be greater then 0");
}
m_baseStream = baseStream ?? throw new ArgumentNullException(nameof(baseStream));
Length = compressedSize;
m_inputLeft = compressedSize;
m_phase = DecodePhase.ReadToken;
m_leaveOpen = leaveOpen;
}
~Lz4DecodeStream()
{
Dispose(false);
}
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
using (MemoryStream stream = new MemoryStream(buffer, offset, count))
{
return (int)Read(stream, count);
}
}
public long Read(Stream stream, long count)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (count <= 0)
{
throw new ArgumentException(nameof(count));
}
long readLeft = count;
while (true)
{
switch (m_phase)
{
case DecodePhase.ReadToken:
{
int token = ReadInputByte();
m_literalLength = token >> 4;
m_matchLength = (token & 0xF) + 4;
if (m_literalLength == 0)
{
goto case DecodePhase.ReadMatch;
}
if (m_literalLength == 0xF)
{
goto case DecodePhase.ReadExLiteralLength;
}
goto case DecodePhase.CopyLiteral;
}
case DecodePhase.ReadExLiteralLength:
{
int exLiteralLength;
do
{
exLiteralLength = ReadInputByte();
m_literalLength += exLiteralLength;
} while (exLiteralLength == byte.MaxValue);
goto case DecodePhase.CopyLiteral;
}
case DecodePhase.CopyLiteral:
{
if (m_literalLength >= readLeft)
{
Write(stream, (int)readLeft);
m_literalLength -= (int)readLeft;
readLeft = 0;
m_phase = DecodePhase.CopyLiteral;
goto case DecodePhase.Finish;
}
Write(stream, m_literalLength);
readLeft -= m_literalLength;
goto case DecodePhase.ReadMatch;
}
case DecodePhase.ReadMatch:
{
m_matchDestination = ReadInputInt16();
if (m_matchLength == 0xF + 4)
{
goto case DecodePhase.ReadExMatchLength;
}
goto case DecodePhase.CopyMatch;
}
case DecodePhase.ReadExMatchLength:
{
int exMatchLength;
do
{
exMatchLength = ReadInputByte();
m_matchLength += exMatchLength;
} while (exMatchLength == byte.MaxValue);
goto case DecodePhase.CopyMatch;
}
case DecodePhase.CopyMatch:
{
int toCopyTotal = m_matchLength < readLeft ? m_matchLength : (int)readLeft;
while (toCopyTotal > 0)
{
int srcPosition = (m_decodeBufferPosition - m_matchDestination) & DecodeBufferMask;
int srcAvailable = DecodeBufferCapacity - srcPosition;
int destAvailable = DecodeBufferCapacity - m_decodeBufferPosition;
int available = srcAvailable < destAvailable ? srcAvailable : destAvailable;
int toCopy = toCopyTotal < available ? toCopyTotal : available;
int delta = m_decodeBufferPosition - srcPosition;
if (delta > 0 && delta < toCopy)
{
for (int i = 0; i < toCopy; i++)
{
m_decodeBuffer[m_decodeBufferPosition++] = m_decodeBuffer[srcPosition++];
}
}
else
{
Buffer.BlockCopy(m_decodeBuffer, srcPosition, m_decodeBuffer, m_decodeBufferPosition, toCopy);
m_decodeBufferPosition += toCopy;
}
toCopyTotal -= toCopy;
m_matchLength -= toCopy;
readLeft -= toCopy;
if (m_decodeBufferPosition == DecodeBufferCapacity)
{
FillOutputStream(stream);
}
}
if (readLeft == 0)
{
m_phase = DecodePhase.CopyMatch;
goto case DecodePhase.Finish;
}
goto case DecodePhase.ReadToken;
}
case DecodePhase.Finish:
{
FillOutputStream(stream);
return count - readLeft;
}
default:
throw new Exception($"Unknonw decode phase {m_phase}");
}
}
}
public void ReadBuffer(byte[] buffer, int offset, int count)
{
using (MemoryStream stream = new MemoryStream(buffer, offset, count))
{
ReadBuffer(stream, count);
}
}
public void ReadBuffer(Stream stream, long count)
{
int read = (int)Read(stream, count);
if (read != count)
{
throw new Exception($"Unexpected end of input stream. Read {read} but expected {count}");
}
if (IsDataLeft)
{
throw new Exception($"Some data left");
}
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
protected override void Dispose(bool disposing)
{
if (!m_leaveOpen)
{
m_baseStream.Dispose();
}
base.Dispose(disposing);
}
// =====================================
// Buffer processing
// =====================================
private int ReadInputByte()
{
if (m_inputBufferPosition == InputBufferCapacity)
{
FillInputBuffer();
}
return m_inputBuffer[m_inputBufferPosition++];
}
private int ReadInputInt16()
{
int available = InputBufferCapacity - m_inputBufferPosition;
if (available == 0)
{
FillInputBuffer();
}
else if (available == 1)
{
m_inputBuffer[0] = m_inputBuffer[m_inputBufferPosition];
FillInputBuffer(1);
}
int ret = m_inputBuffer[m_inputBufferPosition++];
ret |= m_inputBuffer[m_inputBufferPosition++] << 8;
return ret;
}
private void Write(Stream stream, int count)
{
while (count > 0)
{
if (m_inputBufferPosition == InputBufferCapacity)
{
FillInputBuffer();
}
int srcAvailable = InputBufferCapacity - m_inputBufferPosition;
int destAvailable = DecodeBufferCapacity - m_decodeBufferPosition;
int available = srcAvailable < destAvailable ? srcAvailable : destAvailable;
int toWrite = count < available ? count : available;
Buffer.BlockCopy(m_inputBuffer, m_inputBufferPosition, m_decodeBuffer, m_decodeBufferPosition, toWrite);
count -= toWrite;
m_inputBufferPosition += toWrite;
m_decodeBufferPosition += toWrite;
if (m_decodeBufferPosition == DecodeBufferCapacity)
{
FillOutputStream(stream);
}
}
}
private void FillInputBuffer(int offset = 0)
{
int available = InputBufferCapacity - offset;
int count = available < m_inputLeft ? available : (int)m_inputLeft;
m_inputBufferPosition = 0;
while (count > 0)
{
int read = m_baseStream.Read(m_inputBuffer, offset, count);
if (read == 0)
{
#if STREAMING_INPUT
#error TODO: set processing to false and go to finish
#else
throw new Exception("No data left");
#endif
}
m_position += read;
offset += read;
count -= read;
m_inputLeft -= read;
}
}
private void FillOutputStream(Stream stream)
{
int toWriteTotal = m_decodeBufferPosition - m_decodeBufferStart;
int toEnd = DecodeBufferCapacity - m_decodeBufferStart;
int toWrite = toEnd < toWriteTotal ? toEnd : toWriteTotal;
stream.Write(m_decodeBuffer, m_decodeBufferStart, toWrite);
stream.Write(m_decodeBuffer, 0, toWriteTotal - toWrite);
m_decodeBufferPosition = m_decodeBufferPosition & DecodeBufferMask;
m_decodeBufferStart = m_decodeBufferPosition;
}
public bool IsDataLeft => m_phase == DecodePhase.CopyLiteral ? (m_literalLength != 0) : (m_matchLength != 0);
public override bool CanSeek => false;
public override bool CanRead => true;
public override bool CanWrite => false;
public override long Length { get; }
public override long Position
{
get => m_position;
set => throw new NotSupportedException();
}
private const int InputBufferCapacity = 4096;
private const int DecodeBufferCapacity = 0x10000;
private const int DecodeBufferMask = 0xFFFF;
private readonly byte[] m_inputBuffer = new byte[InputBufferCapacity];
private readonly byte[] m_decodeBuffer = new byte[DecodeBufferCapacity];
private readonly Stream m_baseStream;
private readonly bool m_leaveOpen;
private long m_position = 0;
private long m_inputLeft = 0;
private int m_inputBufferPosition = InputBufferCapacity;
private int m_decodeBufferPosition = 0;
/// <summary>
/// State within interruptable phases and across phase boundaries is kept here - again, so that we can punt out and restart freely
/// </summary>
private DecodePhase m_phase;
private int m_literalLength;
private int m_matchLength;
private int m_matchDestination;
private int m_decodeBufferStart;
}