Repository navigation
Expand file tree
/
Copy pathzDeflate.cs
More file actions
1860 lines (1661 loc) · 73.4 KB
/
Copy pathzDeflate.cs
File metadata and controls
1860 lines (1661 loc) · 73.4 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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region License
/* zlib.h -- interface of the 'zlib' general purpose compression library
version 1.2.13, October 13th, 2022
Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
The data format used by the zlib library is described by RFCs (Request for
Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
(zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text.RegularExpressions;
using DeflateLib.Internal;
namespace DeflateLib
{
public class zDeflate : zStream
{
#region Delegates
private delegate block_state CompressFunc(zDeflate z, zFlush flush);
#endregion
#region Constants
/// <summary>
/// If you use the zlib library in a product, an acknowledgment is welcome
/// in the documentation of your product.If for some reason you cannot
/// include such an acknowledgment, I would appreciate that you keep this
/// copyright string in the executable of your product.
/// </summary>
public static readonly string deflate_copyright = "Deflate 1.2.13 Copyright 1995-2022 Jean-loup Gailly and Mark Adler";
/// <summary>
/// Number of length codes, not counting the special END_BLOCK code
/// </summary>
private const int LENGTH_CODES = 29;
/// <summary>
/// Number of literal bytes 0..255
/// </summary>
internal const int LITERALS = 256;
/// <summary>
/// Number of Literal or Length codes, including the END_BLOCK code
/// </summary>
internal const int L_CODES = (LITERALS + 1 + LENGTH_CODES);
/// <summary>
/// Number of distance codes
/// </summary>
internal const int D_CODES = 30;
/// <summary>
/// Number of codes used to transfer the bit lengths
/// </summary>
internal const int BL_CODES = 19;
/// <summary>
/// Maximum heap size
/// </summary>
internal const int HEAP_SIZE = (2 * L_CODES + 1);
/// <summary>
/// All codes must not exceed MAX_BITS bits
/// </summary>
internal const int MAX_BITS = 15;
/// <summary>
/// Size of bit buffer in bi_buf
/// </summary>
internal const int Buf_size = 16;
/// <summary>
/// Minimum amount of lookahead, except at the end of the input file.
/// </summary>
private const int MIN_LOOKAHEAD = zUtil.MAX_MATCH + zUtil.MIN_MATCH + 1;
/// <summary>
/// Number of bytes after end of data in window to initialize in order to avoid
/// memory checker errors from longest match routines
/// </summary>
private const int WIN_INIT = zUtil.MAX_MATCH;
private const int TOO_FAR = 4096;
/// <summary>
/// Maximum stored block length in deflate format (not including header).
/// </summary>
private const int MAX_STORED = 65535;
/// <summary>
/// Table that configures compression level 0 to 9
/// </summary>
#if FASTEST
private static readonly Config[] configuration_table = new Config[]
{
/* good lazy nice chain */
/* 0 */ new Config( 0, 0, 0, 0, deflate_stored), /* store only */
/* 1 */ new Config( 4, 4, 8, 4, deflate_fast), /* max speed, no lazy matches */
};
#else
private static readonly Config[] configuration_table = new Config[]
{
/* good lazy nice chain */
/* 0 */ new Config( 0, 0, 0, 0, deflate_stored), /* store only */
/* 1 */ new Config( 4, 4, 8, 4, deflate_fast), /* max speed, no lazy matches */
/* 2 */ new Config( 4, 5, 16, 8, deflate_fast),
/* 3 */ new Config( 4, 6, 32, 32, deflate_fast),
/* 4 */ new Config( 4, 4, 16, 16, deflate_slow), /* lazy matches */
/* 5 */ new Config( 8, 16, 32, 32, deflate_slow),
/* 6 */ new Config( 8, 16, 128, 128, deflate_slow),
/* 7 */ new Config( 8, 32, 128, 256, deflate_slow),
/* 8 */ new Config(32, 128, 258, 1024, deflate_slow),
/* 9 */ new Config(32, 258, 258, 4096, deflate_slow), /* max compression */
};
#endif
#endregion
#region Variables
private DeflateState _state;
#endregion
#region Init
public zDeflate(zCOMPRESSION level = zCOMPRESSION.DEFAULT,
int method = zConstants.Z_DEFLATED,
int windowBits = zConstants.MAX_WBITS,
int memLevel = zUtil.DEF_MEM_LEVEL,
zSTRATEGY strategy = zSTRATEGY.DEFAULT,
string version = zConstants.ZLIB_VERSION)
{
var ret = deflateInit2(level, method, windowBits, memLevel, strategy, version);
if (ret != zRetCode.Z_OK)
{
ERR_RETURN(ret);
throw new Exception(msg);
}
}
private zRetCode deflateInit2(zCOMPRESSION level,
int method,
int windowBits,
int memLevel,
zSTRATEGY strategy,
string version)
{
int wrap = 1;
if (version == null || version[0] != zConstants.ZLIB_VERSION[0])
return zRetCode.Z_VERSION_ERROR;
msg = null;
#if FASTEST
if (level != 0) level = zCOMPRESSION.LEVEL_1;
#else
if (level == zCOMPRESSION.DEFAULT)
level = zCOMPRESSION.LEVEL_6;
#endif
if (windowBits < 0) /* suppress zlib wrapper */
{
wrap = 0;
if (windowBits < -15)
return zRetCode.Z_STREAM_ERROR;
windowBits = -windowBits;
}
#if GZIP
else if (windowBits > 15)
{
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
#endif
if (memLevel < 1 || memLevel > zConstants.MAX_MEM_LEVEL ||
method != zConstants.Z_DEFLATED || windowBits < 8 ||
windowBits > 15 || level < zCOMPRESSION.NO ||
level > zCOMPRESSION.BEST || strategy < zSTRATEGY.DEFAULT
|| strategy > zSTRATEGY.FIXED || (windowBits == 8 && wrap != 1))
{
throw new ArgumentException("Parameter error");
}
if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
_state = new DeflateState();
_state.strm = this;
_state.status = DeflateStatus.INIT; /* to pass state test in deflateReset() */
_state.wrap = wrap;
_state.gzhead = null;
_state.w_bits = (uint)windowBits;
_state.w_size = 1 << windowBits;
_state.w_mask = _state.w_size - 1;
_state.hash_bits = memLevel + 7;
_state.hash_size = 1 << (_state.hash_bits);
_state.hash_mask = _state.hash_size - 1;
_state.hash_shift = (int) ((_state.hash_bits + zUtil.MIN_MATCH - 1u) / zUtil.MIN_MATCH);
_state.window = new byte[_state.w_size * 2];
_state.prev = new ushort[_state.w_size];
_state.head = new ushort[_state.hash_size];
// Zero because nothing written to s->window yet
_state.high_water = 0;
// 16K elements by default
_state.lit_bufsize = 1u << (memLevel + 6);
/* We overlay pending_buf and sym_buf. This works since the average size
* for length/distance pairs over any compressed block is assured to be 31
* bits or less.
*
* Analysis: The longest fixed codes are a length code of 8 bits plus 5
* extra bits, for lengths 131 to 257. The longest fixed distance codes are
* 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
* possible fixed-codes length/distance pair is then 31 bits total.
*
* sym_buf starts one-fourth of the way into pending_buf. So there are
* three bytes in sym_buf for every four bytes in pending_buf. Each symbol
* in sym_buf is three bytes -- two for the distance and one for the
* literal/length. As each symbol is consumed, the pointer to the next
* sym_buf value to read moves forward three bytes. From that symbol, up to
* 31 bits are written to pending_buf. The closest the written pending_buf
* bits gets to the next sym_buf symbol to read is just before the last
* code is written. At that time, 31*(n - 2) bits have been written, just
* after 24*(n - 2) bits have been consumed from sym_buf. sym_buf starts at
* 8*n bits into pending_buf. (Note that the symbol buffer fills when n - 1
* symbols are written.) The closest the writing gets to what is unread is
* then n + 14 bits. Here n is lit_bufsize, which is 16384 by default, and
* can range from 128 to 32768.
*
* Therefore, at a minimum, there are 142 bits of space between what is
* written and what is read in the overlain buffers, so the symbols cannot
* be overwritten by the compressed data. That space is actually 139 bits,
* due to the three-bit fixed-code block header.
*
* That covers the case where either Z_FIXED is specified, forcing fixed
* codes, or when the use of fixed codes is chosen, because that choice
* results in a smaller compressed block than dynamic codes. That latter
* condition then assures that the above analysis also covers all dynamic
* blocks. A dynamic-code block will only be chosen to be emitted if it has
* fewer bits than a fixed-code block would for the same set of symbols.
* Therefore its average symbol length is assured to be less than 31. So
* the compressed data for a dynamic block also cannot overwrite the
* symbols from which it is being constructed.
*/
//Impl detail: Original uses pointers, we use counters into "buffer"
_state.buffer = new byte[_state.lit_bufsize * 4];
//_state.pending_buf_size = (uint)_state.buffer.Length;
//_state.pending_buf = 0;
_state.sym_buf = _state.lit_bufsize;
/* We avoid equality with lit_bufsize*3 because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
_state.sym_end = (_state.lit_bufsize - 1u) * 3u;
_state.level = (int)level;
_state.strategy = strategy;
_state.method = (byte)method;
return deflateReset();
}
internal zRetCode deflateReset()
{
zRetCode ret = deflateResetKeep();
if (ret == zRetCode.Z_OK)
lm_init(_state);
return ret;
}
internal zRetCode deflateResetKeep()
{
if (deflateStateCheck())
{
return zRetCode.Z_STREAM_ERROR;
}
total_in = total_out = 0;
msg = null;
data_type = (int) zDataType.UNKNOWN;
var s = _state;
s.pending = 0;
s.pending_out = s.pending_buf;
if (s.wrap < 0)
{
s.wrap -= s.wrap; /* was made negative by deflate(..., Z_FINISH); */
}
s.status =
#if GZIP
s.wrap == 2 ? DeflateStatus.GZIP :
#endif
DeflateStatus.INIT;
adler =
#if GZIP
s.wrap == 2 ? CRC32.Update(0u, null, 0, 0) :
#endif
Adler32.Compute(0, null, 0, 0);
s.last_flush = (zFlush) (-2);
DeflateTrees.tr_init(s);
return zRetCode.Z_OK;
}
private void lm_init(DeflateState s)
{
s.window_size = 2 * s.w_size;
CLEAR_HASH(s);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = zUtil.MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
/// <summary>
/// Check for a valid deflate stream state.
/// </summary>
/// <returns>False if all OK</returns>
private bool deflateStateCheck()
{
var s = _state;
return (s == null || s.strm != this || (s.status != DeflateStatus.INIT &&
s.status != DeflateStatus.GZIP &&
s.status != DeflateStatus.EXTRA &&
s.status != DeflateStatus.NAME &&
s.status != DeflateStatus.COMMENT &&
s.status != DeflateStatus.HCRC &&
s.status != DeflateStatus.BUSY &&
s.status != DeflateStatus.FINISH));
}
private static void CLEAR_HASH(DeflateState s)
{
for (int c = 0; c < s.head.Length; c++) s.head[c] = 0;
}
#endregion
#region Deflate
public zRetCode Deflate(zFlush flush)
{
// Value of flush param for previous deflate call
zFlush old_flush;
if (deflateStateCheck() || flush > zFlush.Z_BLOCK || flush < zFlush.Z_NO_FLUSH)
{
return zRetCode.Z_STREAM_ERROR;
}
var s = _state;
if (_out == null ||
(avail_in != 0 && _in == null) ||
(s.status == DeflateStatus.FINISH && flush != zFlush.Z_FINISH))
{
return ERR_RETURN(zRetCode.Z_STREAM_ERROR);
}
if (avail_out == 0) return ERR_RETURN(zRetCode.Z_BUF_ERROR);
old_flush = s.last_flush;
s.last_flush = flush;
/* Flush as much pending output as possible */
if (s.pending != 0)
{
flush_pending();
if (avail_out == 0)
{
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = (zFlush) (-1);
return zRetCode.Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
flush != zFlush.Z_FINISH)
{
return ERR_RETURN(zRetCode.Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status == DeflateStatus.FINISH && avail_in != 0)
{
return ERR_RETURN(zRetCode.Z_BUF_ERROR);
}
/* Write the header */
if (s.wrap == 0 && s.status == DeflateStatus.INIT)
s.status = DeflateStatus.BUSY;
else if (s.status == DeflateStatus.INIT)
{
/* zlib header */
uint header = (zConstants.Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
uint level_flags;
if (s.strategy >= zSTRATEGY.HUFFMAN_ONLY || s.level < 2)
level_flags = 0;
else if (s.level < 6)
level_flags = 1;
else if (s.level == 6)
level_flags = 2;
else
level_flags = 3;
header |= (level_flags << 6);
if (s.strstart != 0) header |= zConstants.PRESET_DICT;
header += 31 - (header % 31);
putShortMSB(header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart != 0)
{
putShortMSB((uint)(adler >> 16));
putShortMSB((uint)(adler & 0xffff));
}
adler = Adler32.Compute(0, null, 0, 0);
s.status = DeflateStatus.BUSY;
flush_pending();
if (s.pending != 0)
{
s.last_flush = (zFlush)(-1);
return zRetCode.Z_OK;
}
}
#if GZIP
if (s.status == DeflateStatus.GZIP)
{
/* gzip header */
adler = CRC32.Update(0, null, 0, 0);
s.put_byte(31);
s.put_byte(139);
s.put_byte(8);
if (s.gzhead == null)
{
s.put_byte(0);
s.put_byte(0);
s.put_byte(0);
s.put_byte(0);
s.put_byte(0);
s.put_byte((byte) (s.level == 9 ? 2 :
(s.strategy >= zSTRATEGY.HUFFMAN_ONLY || s.level < 2 ?
4 : 0)));
s.put_byte(zUtil.OS_CODE);
s.status = DeflateStatus.BUSY;
/* Compression must start with an empty pending buffer */
flush_pending();
if (s.pending != 0)
{
s.last_flush = (zFlush)(-1);
return zRetCode.Z_OK;
}
}
else
{
s.put_byte((byte) ((s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(s.gzhead.extra == null ? 0 : 4) +
(s.gzhead.name == null ? 0 : 8) +
(s.gzhead.comment == null ? 0 : 16)
));
s.put_byte((Byte)(s.gzhead.time & 0xff));
s.put_byte((Byte)((s.gzhead.time >> 8) & 0xff));
s.put_byte((Byte)((s.gzhead.time >> 16) & 0xff));
s.put_byte((Byte)((s.gzhead.time >> 24) & 0xff));
s.put_byte((byte)(s.level == 9 ? 2 :
(s.strategy >= zSTRATEGY.HUFFMAN_ONLY || s.level < 2 ?
4 : 0)));
s.put_byte((byte) (s.gzhead.os & 0xff));
if (s.gzhead.extra != null)
{
s.put_byte((byte) (s.gzhead.extra_len & 0xff));
s.put_byte((byte) ((s.gzhead.extra_len >> 8) & 0xff));
}
if (s.gzhead.hcrc)
adler = CRC32.Update(adler, s.buffer, s.pending_buf, s.pending);
s.gzindex = 0;
s.status = DeflateStatus.EXTRA;
}
}
if (s.status == DeflateStatus.EXTRA)
{
if (s.gzhead.extra != null)
{
var beg = s.pending; /* start of bytes to update crc */
int left = ((s.gzhead.extra_len & 0xffff) - s.gzindex);
while (s.pending + left > s.pending_buf_size)
{
int copy = s.pending_buf_size - s.pending;
Buffer.BlockCopy(s.gzhead.extra, s.gzindex,
s.buffer, (/*s.pending_buf +*/ s.pending), copy);
s.pending = s.pending_buf_size;
HCRC_UPDATE(beg);
s.gzindex += copy;
flush_pending();
if (s.pending != 0)
{
s.last_flush = (zFlush) (-1);
return zRetCode.Z_OK;
}
beg = 0;
left -= copy;
}
Buffer.BlockCopy(s.gzhead.extra, s.gzindex,
s.buffer, (/*s.pending_buf +*/ s.pending), left);
s.pending += left;
HCRC_UPDATE(beg);
s.gzindex = 0;
}
s.status = DeflateStatus.NAME;
}
if (s.status == DeflateStatus.NAME)
{
if (s.gzhead.name != null)
{
int beg = s.pending;
int val;
do
{
if (s.pending == s.pending_buf_size)
{
HCRC_UPDATE(beg);
flush_pending();
if (s.pending != 0)
{
s.last_flush = (zFlush)(-1);
return zRetCode.Z_OK;
}
beg = 0;
}
val = s.gzhead.name[s.gzindex++];
s.put_byte((byte) val);
} while (val != 0);
HCRC_UPDATE(beg);
s.gzindex = 0;
}
s.status = DeflateStatus.COMMENT;
}
if (s.status == DeflateStatus.COMMENT)
{
if (s.gzhead.comment != null)
{
int beg = s.pending;
int val;
do
{
if (s.pending == s.pending_buf_size)
{
HCRC_UPDATE(beg);
flush_pending();
if (s.pending != 0)
{
s.last_flush = (zFlush)(-1);
return zRetCode.Z_OK;
}
beg = 0;
}
val = s.gzhead.comment[s.gzindex++];
s.put_byte((byte)val);
} while (val != 0);
HCRC_UPDATE(beg);
}
s.status = DeflateStatus.HCRC;
}
if (s.status == DeflateStatus.HCRC)
{
if (s.gzhead.hcrc)
{
if (s.pending + 2 > s.pending_buf_size)
{
flush_pending();
if (s.pending != 0)
{
s.last_flush = (zFlush)(-1);
return zRetCode.Z_OK;
}
}
s.put_byte((byte)(adler & 0xff));
s.put_byte((byte)((adler >> 8) & 0xff));
adler = CRC32.Update(0, null, 0, 0);
}
s.status = DeflateStatus.BUSY;
/* Compression must start with an empty pending buffer */
flush_pending();
if (s.pending != 0)
{
s.last_flush = (zFlush)(-1);
return zRetCode.Z_OK;
}
}
#endif
/* Start a new block or continue the current one.
*/
if (avail_in != 0 || s.lookahead != 0 ||
(flush != zFlush.Z_NO_FLUSH && s.status != DeflateStatus.FINISH))
{
block_state bstate =
s.level == 0 ? deflate_stored(this, flush) :
s.strategy == zSTRATEGY.HUFFMAN_ONLY ? deflate_huff(this, flush) :
s.strategy == zSTRATEGY.RLE ? deflate_rle(this, flush) :
configuration_table[s.level].func(this, flush);
if (bstate == block_state.finish_started || bstate == block_state.finish_done)
{
s.status = DeflateStatus.FINISH;
}
if (bstate == block_state.need_more || bstate == block_state.finish_started)
{
if (avail_out == 0)
{
s.last_flush = (zFlush)(-1); /* avoid BUF_ERROR next call, see above */
}
return zRetCode.Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate == block_state.block_done)
{
if (flush == zFlush.Z_PARTIAL_FLUSH)
{
DeflateTrees.tr_align(s);
}
/* FULL_FLUSH or SYNC_FLUSH */
else if (flush != zFlush.Z_BLOCK)
{
DeflateTrees.stored_block(s, null, 0, 0, 0);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush == zFlush.Z_FULL_FLUSH)
{
CLEAR_HASH(s); /* forget history */
if (s.lookahead == 0)
{
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending();
if (avail_out == 0)
{
s.last_flush = (zFlush)(-1); /* avoid BUF_ERROR next call, see above */
return zRetCode.Z_OK;
}
}
}
if (flush != zFlush.Z_FINISH) return zRetCode.Z_OK;
if (s.wrap <= 0) return zRetCode.Z_STREAM_END;
// Write the trailer
#if GZIP
if (s.wrap == 2)
{
s.put_byte((byte)(adler & 0xff));
s.put_byte((byte)((adler >> 8) & 0xff));
s.put_byte((byte)((adler >> 16) & 0xff));
s.put_byte((byte)((adler >> 24) & 0xff));
s.put_byte((byte)(total_in & 0xff));
s.put_byte((byte)((total_in >> 8) & 0xff));
s.put_byte((byte)((total_in >> 16) & 0xff));
s.put_byte((byte)((total_in >> 24) & 0xff));
}
else
#endif
{
putShortMSB((uint)(adler >> 16));
putShortMSB((uint)(adler & 0xffff));
}
flush_pending();
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) s.wrap = -s.wrap; /* write the trailer only once! */
return s.pending != 0 ? zRetCode.Z_OK : zRetCode.Z_STREAM_END;
}
public zRetCode DeflateEnd()
{
if (deflateStateCheck()) return zRetCode.Z_STREAM_ERROR;
var status = _state.status;
_state.buffer = null;
_state = null;
return status == DeflateStatus.BUSY ? zRetCode.Z_DATA_ERROR : zRetCode.Z_OK;
}
private void flush_pending()
{
var s = _state;
DeflateTrees.flush_bits(s);
var len = s.pending;
if (len > avail_out)
{
len = avail_out;
}
if (len == 0) return;
Buffer.BlockCopy(s.buffer, s.pending_out, _out, next_out, len);
next_out += len;
s.pending_out += len;
total_out += len;
avail_out -= len;
s.pending -= len;
if (s.pending == 0)
{
s.pending_out = s.pending_buf;
}
}
/// <summary>
/// Put a short in the pending buffer. The 16-bit value is put in MSB order.
/// IN assertion: the stream state is correct and there is enough room in
/// pending_buf.
/// </summary>
private void putShortMSB(uint b)
{
_state.put_byte((byte)(b >> 8));
_state.put_byte((byte)(b & 0xff));
}
#endregion
#region Deflate store
/// <summary>
/// Copy without compression as much as possible from the input stream, return
/// the current block state.
///
/// In case deflateParams() is used to later switch to a non-zero compression
/// level, s->matches (otherwise unused when storing) keeps track of the number
/// of hash table slides to perform.If s->matches is 1, then one hash table
/// slide will be done when switching.If s->matches is 2, the maximum value
/// allowed here, then the hash table will be cleared, since two or more slides
/// is the same as a clear.
///
/// deflate_stored() is written to minimize the number of times an input byte is
/// copied.It is most efficient with large input and output buffers, which
/// maximizes the opportunities to have a single copy from next_in to next_out.
/// </summary>
private static block_state deflate_stored(zDeflate z, zFlush flush)
{
return z.deflate_stored(z._state, flush);
}
private block_state deflate_stored(DeflateState s, zFlush flush)
{
// Smallest worthy block size when not flushing or finishing. By default
// this is 32K. This can be as small as 507 bytes for memLevel == 1. For
// large input and output buffers, the stored block size will be larger.
int min_block = Math.Min(s.pending_buf_size - 5, s.w_size);
// Copy as many min_block or larger stored blocks directly to next_out as
// possible. If flushing, copy the remaining available input to next_out as
// stored blocks, if there is enough space.
int len, have;
int left;
int last = 0;
int used = avail_in;
do
{
// Set len to the maximum size block that we can copy directly with the
// available input data and output space. Set left to how much of that
// would be copied from what's left in the window.
len = MAX_STORED; // Maximum deflate stored block length
have = (s.bi_valid + 42) >> 3; // Number of header bytes
if (avail_out < have) // Need room for header
break;
// Maximum stored block length that will fit in avail_out:
have = avail_out - have;
left = (int) s.strstart - s.block_start; // Bytes left in window
if (len > left + avail_in)
len = left + avail_in; // Limit len to the input
if (len > have)
len = have; // Limit len to the output
// If the stored block would be less than min_block in length, or if
// unable to copy all of the available input when flushing, then try
// copying to the window and the pending buffer instead. Also don't
// write an empty block when flushing -- deflate() does that.
if (len < min_block && ((len == 0 && flush != zFlush.Z_FINISH) ||
flush == zFlush.Z_NO_FLUSH ||
len != left + avail_in))
break;
// Make a dummy stored block in pending to get the header bytes,
// including any pending bits. This also updates the debugging counts.
last = flush == zFlush.Z_FINISH && len == left + avail_in ? 1 : 0;
DeflateTrees.stored_block(s, null, 0, 0, last);
// Replace the lengths in the dummy stored block with len.
s.buffer[/*s.pending_buf +*/ s.pending - 4] = (byte) len;
s.buffer[/*s.pending_buf +*/ s.pending - 3] = (byte) (len >> 8);
s.buffer[/*s.pending_buf +*/ s.pending - 2] = (byte) ~len;
s.buffer[/*s.pending_buf +*/ s.pending - 1] = (byte) (~len >> 8);
// Write the stored block header bytes.
flush_pending();
#if ZLIB_DEBUG
// Update debugging counts for the data about to be copied.
s.compressed_len += len << 3;
s.bits_sent += len << 3;
#endif
// Copy uncompressed bytes from the window to next_out.
if (left != 0)
{
if (left > len)
left = (int) len;
Buffer.BlockCopy(s.window, s.block_start, _out, next_out, left);
next_out += left;
avail_out -= left;
total_out += left;
s.block_start += left;
len -= left;
}
// Copy uncompressed bytes directly from next_in to next_out, updating
// the check value.
if (len != 0)
{
read_buf(_out, next_out, (int) len);
next_out += (int)len;
avail_out -= len;
total_out += len;
}
} while (last == 0);
// Update the sliding window with the last s->w_size bytes of the copied
// data, or append all of the copied data to the existing window if less
// than s->w_size bytes were copied. Also update the number of bytes to
// insert in the hash tables, in the event that deflateParams() switches to
// a non-zero compression level.
used -= avail_in; // number of input bytes directly copied
if (used != 0)
{
// If any input was used, then no unused input remains in the window,
// therefore s->block_start == s->strstart.
if (used >= s.w_size)
{ // supplant the previous history
s.matches = 2; // clear hash
Buffer.BlockCopy(_in, (int) (next_in - s.w_size), s.window, 0, (int) s.w_size);
s.strstart = s.w_size;
s.insert = s.strstart;
}
else
{
if (s.window_size - s.strstart <= used)
{
// Slide the window down.
s.strstart -= s.w_size;
Buffer.BlockCopy(s.window, (int) s.w_size, s.window, 0, (int) s.strstart);
if (s.matches < 2)
s.matches++; // add a pending slide_hash()
if (s.insert > s.strstart)
s.insert = s.strstart;
}
Buffer.BlockCopy(_in, (int) (next_in - used), s.window, (int) s.strstart, (int) used);
s.strstart += used;
s.insert += Math.Min(used, s.w_size - s.insert);
}
s.block_start = (int) s.strstart;
}
if (s.high_water < s.strstart)
s.high_water = s.strstart;
// If the last block was written to next_out, then done.
if (last != 0)
return block_state.finish_done;
// If flushing and all input has been consumed, then done.
if (flush != zFlush.Z_NO_FLUSH && flush != zFlush.Z_FINISH &&
avail_in == 0 && (int)s.strstart == s.block_start)
return block_state.block_done;
// Fill the window with any remaining input.
have = s.window_size - s.strstart;
if (avail_in > have && s.block_start >= (int)s.w_size)
{
// Slide the window down.
s.block_start -= (int) s.w_size;
s.strstart -= s.w_size;
Buffer.BlockCopy(s.window, (int) s.w_size, s.window, 0, (int) s.strstart);
if (s.matches < 2)
s.matches++; // add a pending slide_hash()
have += s.w_size; // more space now
if (s.insert > s.strstart)
s.insert = s.strstart;
}
if (have > avail_in)
have = avail_in;
if (have != 0)
{
read_buf(s.window, (int) s.strstart, (int) have);
s.strstart += have;
s.insert += Math.Min(have, s.w_size - s.insert);
}
if (s.high_water < s.strstart)
s.high_water = s.strstart;
// There was not enough avail_out to write a complete worthy or flushed
// stored block to next_out. Write a stored block to pending instead, if we
// have enough input for a worthy block, or if flushing and there is enough
// room for the remaining input as a stored block in the pending buffer.
have = (s.bi_valid + 42) >> 3; // number of header bytes
// Maximum stored block length that will fit in pending:
have = Math.Min(s.pending_buf_size - have, MAX_STORED);
min_block = Math.Min(have, s.w_size);
left = (int) (s.strstart - s.block_start);
if (left >= min_block ||
((left != 0 || flush == zFlush.Z_FINISH) && flush != zFlush.Z_NO_FLUSH &&
avail_in == 0 && left <= have))
{
len = Math.Min(left, have);
last = flush == zFlush.Z_FINISH && avail_in == 0 &&
len == left ? 1 : 0;
DeflateTrees.stored_block(s, s.window, s.block_start, len, last);
s.block_start += (int) len;
flush_pending();
}