2
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
4
Redistribution and use in source and binary forms, with or without
5
modification, are permitted provided that the following conditions are met:
7
1. Redistributions of source code must retain the above copyright notice,
8
this list of conditions and the following disclaimer.
10
2. Redistributions in binary form must reproduce the above copyright
11
notice, this list of conditions and the following disclaimer in
12
the documentation and/or other materials provided with the distribution.
14
3. The names of the authors may not be used to endorse or promote products
15
derived from this software without specific prior written permission.
17
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
18
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
19
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
20
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
21
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
26
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
This program is based on zlib-1.1.3, so all credit should go authors
29
Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
30
and contributors of zlib.
38
public sealed class Deflate
40
private const int MAX_MEM_LEVEL = 9;
42
private const int Z_DEFAULT_COMPRESSION = -1;
44
private const int MAX_WBITS = 15;
46
private const int DEF_MEM_LEVEL = 8;
50
internal int good_length;
52
internal int max_lazy;
54
internal int nice_length;
56
internal int max_chain;
60
internal Config(int good_length, int max_lazy, int nice_length, int max_chain, int
64
// reduce lazy search above this match length
65
// do not perform lazy search above this match length
66
// quit search above this match length
67
this.good_length = good_length;
68
this.max_lazy = max_lazy;
69
this.nice_length = nice_length;
70
this.max_chain = max_chain;
75
private const int STORED = 0;
77
private const int FAST = 1;
79
private const int SLOW = 2;
81
private static readonly Deflate.Config[] config_table;
85
config_table = new Deflate.Config[10];
86
// good lazy nice chain
87
config_table[0] = new Deflate.Config(0, 0, 0, 0, STORED);
88
config_table[1] = new Deflate.Config(4, 4, 8, 4, FAST);
89
config_table[2] = new Deflate.Config(4, 5, 16, 8, FAST);
90
config_table[3] = new Deflate.Config(4, 6, 32, 32, FAST);
91
config_table[4] = new Deflate.Config(4, 4, 16, 16, SLOW);
92
config_table[5] = new Deflate.Config(8, 16, 32, 32, SLOW);
93
config_table[6] = new Deflate.Config(8, 16, 128, 128, SLOW);
94
config_table[7] = new Deflate.Config(8, 32, 128, 256, SLOW);
95
config_table[8] = new Deflate.Config(32, 128, 258, 1024, SLOW);
96
config_table[9] = new Deflate.Config(32, 258, 258, 4096, SLOW);
99
private static readonly string[] z_errmsg = new string[] { "need dictionary", "stream end"
100
, string.Empty, "file error", "stream error", "data error", "insufficient memory"
101
, "buffer error", "incompatible version", string.Empty };
103
private const int NeedMore = 0;
105
private const int BlockDone = 1;
107
private const int FinishStarted = 2;
109
private const int FinishDone = 3;
111
private const int PRESET_DICT = unchecked((int)(0x20));
113
private const int Z_FILTERED = 1;
115
private const int Z_HUFFMAN_ONLY = 2;
117
private const int Z_DEFAULT_STRATEGY = 0;
119
private const int Z_NO_FLUSH = 0;
121
private const int Z_PARTIAL_FLUSH = 1;
123
private const int Z_SYNC_FLUSH = 2;
125
private const int Z_FULL_FLUSH = 3;
127
private const int Z_FINISH = 4;
129
private const int Z_OK = 0;
131
private const int Z_STREAM_END = 1;
133
private const int Z_NEED_DICT = 2;
135
private const int Z_ERRNO = -1;
137
private const int Z_STREAM_ERROR = -2;
139
private const int Z_DATA_ERROR = -3;
141
private const int Z_MEM_ERROR = -4;
143
private const int Z_BUF_ERROR = -5;
145
private const int Z_VERSION_ERROR = -6;
147
private const int INIT_STATE = 42;
149
private const int BUSY_STATE = 113;
151
private const int FINISH_STATE = 666;
153
private const int Z_DEFLATED = 8;
155
private const int STORED_BLOCK = 0;
157
private const int STATIC_TREES = 1;
159
private const int DYN_TREES = 2;
161
private const int Z_BINARY = 0;
163
private const int Z_ASCII = 1;
165
private const int Z_UNKNOWN = 2;
167
private const int Buf_size = 8 * 2;
169
private const int REP_3_6 = 16;
171
private const int REPZ_3_10 = 17;
173
private const int REPZ_11_138 = 18;
175
private const int MIN_MATCH = 3;
177
private const int MAX_MATCH = 258;
179
private const int MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
181
private const int MAX_BITS = 15;
183
private const int D_CODES = 30;
185
private const int BL_CODES = 19;
187
private const int LENGTH_CODES = 29;
189
private const int LITERALS = 256;
191
private const int L_CODES = (LITERALS + 1 + LENGTH_CODES);
193
private const int HEAP_SIZE = (2 * L_CODES + 1);
195
private const int END_BLOCK = 256;
197
internal ZStream strm;
201
internal byte[] pending_buf;
203
internal int pending_buf_size;
205
internal int pending_out;
207
internal int pending;
209
internal int noheader;
211
internal byte data_type;
213
internal byte method;
215
internal int last_flush;
223
internal byte[] window;
225
internal int window_size;
227
internal short[] prev;
229
internal short[] head;
233
internal int hash_size;
235
internal int hash_bits;
237
internal int hash_mask;
239
internal int hash_shift;
241
internal int block_start;
243
internal int match_length;
245
internal int prev_match;
247
internal int match_available;
249
internal int strstart;
251
internal int match_start;
253
internal int lookahead;
255
internal int prev_length;
257
internal int max_chain_length;
259
internal int max_lazy_match;
263
internal int strategy;
265
internal int good_match;
267
internal int nice_match;
269
internal short[] dyn_ltree;
271
internal short[] dyn_dtree;
273
internal short[] bl_tree;
275
internal Tree l_desc = new Tree();
277
internal Tree d_desc = new Tree();
279
internal Tree bl_desc = new Tree();
281
internal short[] bl_count = new short[MAX_BITS + 1];
283
internal int[] heap = new int[2 * L_CODES + 1];
285
internal int heap_len;
287
internal int heap_max;
289
internal byte[] depth = new byte[2 * L_CODES + 1];
293
internal int lit_bufsize;
295
internal int last_lit;
299
internal int opt_len;
301
internal int static_len;
303
internal int matches;
305
internal int last_eob_len;
307
internal short bi_buf;
309
internal int bi_valid;
317
// Z_STREAM_ERROR (-2)
321
// Z_VERSION_ERROR (-6)
322
// block not completed, need more input or more output
323
// block flush performed
324
// finish started, need only more output at next deflate
325
// finish done, accept no more input or output
326
// preset dictionary flag in zlib header
327
// The deflate compression method
328
// The three kinds of block type
329
// repeat previous bit length 3-6 times (2 bits of repeat count)
330
// repeat a zero length 3-10 times (3 bits of repeat count)
331
// repeat a zero length 11-138 times (7 bits of repeat count)
332
// pointer back to this zlib stream
333
// as the name implies
334
// output still pending
335
// size of pending_buf
336
// next pending byte to output to the stream
337
// nb of bytes in the pending buffer
338
// suppress zlib header and adler32
339
// UNKNOWN, BINARY or ASCII
340
// STORED (for zip only) or DEFLATED
341
// value of flush param for previous deflate call
342
// LZ77 window size (32K by default)
343
// log2(w_size) (8..16)
345
// Sliding window. Input bytes are read into the second half of the window,
346
// and move to the first half later to keep a dictionary of at least wSize
347
// bytes. With this organization, matches are limited to a distance of
348
// wSize-MAX_MATCH bytes, but this ensures that IO is always
349
// performed with a length multiple of the block size. Also, it limits
350
// the window size to 64K, which is quite useful on MSDOS.
351
// To do: use the user input buffer as sliding window.
352
// Actual size of window: 2*wSize, except when the user input buffer
353
// is directly used as sliding window.
354
// Link to older string with same hash index. To limit the size of this
355
// array to 64K, this link is maintained only for the last 32K strings.
356
// An index in this array is thus a window index modulo 32K.
357
// Heads of the hash chains or NIL.
358
// hash index of string to be inserted
359
// number of elements in hash table
362
// Number of bits by which ins_h must be shifted at each input
363
// step. It must be such that after MIN_MATCH steps, the oldest
364
// byte no longer takes part in the hash key, that is:
365
// hash_shift * MIN_MATCH >= hash_bits
366
// Window position at the beginning of the current output block. Gets
367
// negative when the window is moved backwards.
368
// length of best match
370
// set if previous match exists
371
// start of string to insert
372
// start of matching string
373
// number of valid bytes ahead in window
374
// Length of the best match at previous step. Matches not greater than this
375
// are discarded. This is used in the lazy match evaluation.
376
// To speed up deflation, hash chains are never searched beyond this
377
// length. A higher limit improves compression ratio but degrades the speed.
378
// Attempt to find a better match only when the current match is strictly
379
// smaller than this value. This mechanism is used only for compression
381
// Insert new strings in the hash table only if the match length is not
382
// greater than this length. This saves time but degrades compression.
383
// max_insert_length is used only for compression levels <= 3.
384
// compression level (1..9)
385
// favor or force Huffman coding
386
// Use a faster search when the previous match is longer than this
387
// Stop searching when current match exceeds this
388
// literal and length tree
390
// Huffman tree for bit lengths
391
// desc for literal tree
392
// desc for distance tree
393
// desc for bit length tree
394
// number of codes at each bit length for an optimal tree
395
// heap used to build the Huffman trees
396
// number of elements in the heap
397
// element of largest frequency
398
// The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
399
// The same heap array is used to build all trees.
400
// Depth of each subtree used as tie breaker for trees of equal frequency
401
// index for literals or lengths */
402
// Size of match buffer for literals/lengths. There are 4 reasons for
403
// limiting lit_bufsize to 64K:
404
// - frequencies can be kept in 16 bit counters
405
// - if compression is not successful for the first block, all input
406
// data is still in the window so we can still emit a stored block even
407
// when input comes from standard input. (This can also be done for
408
// all blocks if lit_bufsize is not greater than 32K.)
409
// - if compression is not successful for a file smaller than 64K, we can
410
// even emit a stored file instead of a stored block (saving 5 bytes).
411
// This is applicable only for zip (not gzip or zlib).
412
// - creating new Huffman trees less frequently may not provide fast
413
// adaptation to changes in the input data statistics. (Take for
414
// example a binary file with poorly compressible code followed by
415
// a highly compressible string table.) Smaller buffer sizes give
416
// fast adaptation but have of course the overhead of transmitting
417
// trees more frequently.
418
// - I can't count above 4
419
// running index in l_buf
420
// Buffer for distances. To simplify the code, d_buf and l_buf have
421
// the same number of elements. To use different lengths, an extra flag
422
// array would be necessary.
423
// index of pendig_buf
424
// bit length of current block with optimal trees
425
// bit length of current block with static trees
426
// number of string matches in current block
427
// bit length of EOB code for last block
428
// Output buffer. bits are inserted starting at the bottom (least
429
// significant bits).
430
// Number of valid bits in bi_buf. All bits above the last valid bit
432
dyn_ltree = new short[HEAP_SIZE * 2];
433
dyn_dtree = new short[(2 * D_CODES + 1) * 2];
435
bl_tree = new short[(2 * BL_CODES + 1) * 2];
438
// Huffman tree for bit lengths
439
internal void Lm_init()
441
window_size = 2 * w_size;
442
head[hash_size - 1] = 0;
443
for (int i = 0; i < hash_size - 1; i++)
447
// Set the default configuration parameters:
448
max_lazy_match = Deflate.config_table[level].max_lazy;
449
good_match = Deflate.config_table[level].good_length;
450
nice_match = Deflate.config_table[level].nice_length;
451
max_chain_length = Deflate.config_table[level].max_chain;
455
match_length = prev_length = MIN_MATCH - 1;
460
// Initialize the tree data structures for a new zlib stream.
461
internal void Tr_init()
463
l_desc.dyn_tree = dyn_ltree;
464
l_desc.stat_desc = StaticTree.static_l_desc;
465
d_desc.dyn_tree = dyn_dtree;
466
d_desc.stat_desc = StaticTree.static_d_desc;
467
bl_desc.dyn_tree = bl_tree;
468
bl_desc.stat_desc = StaticTree.static_bl_desc;
472
// enough lookahead for inflate
473
// Initialize the first block of the first file:
477
internal void Init_block()
479
// Initialize the trees.
480
for (int i = 0; i < L_CODES; i++)
482
dyn_ltree[i * 2] = 0;
484
for (int i_1 = 0; i_1 < D_CODES; i_1++)
486
dyn_dtree[i_1 * 2] = 0;
488
for (int i_2 = 0; i_2 < BL_CODES; i_2++)
490
bl_tree[i_2 * 2] = 0;
492
dyn_ltree[END_BLOCK * 2] = 1;
493
opt_len = static_len = 0;
494
last_lit = matches = 0;
497
// Restore the heap property by moving down the tree starting at node k,
498
// exchanging a node with the smallest of its two sons if necessary, stopping
499
// when the heap property is re-established (each father smaller than its
501
internal void Pqdownheap(short[] tree, int k)
503
// the tree to restore
508
while (j <= heap_len)
510
// Set j to the smallest of the two sons:
511
if (j < heap_len && Smaller(tree, heap[j + 1], heap[j], depth))
515
// Exit if v is smaller than both sons
516
if (Smaller(tree, v, heap[j], depth))
520
// Exchange v with the smallest son
523
// And continue down the tree, setting j to the left son of k
529
internal static bool Smaller(short[] tree, int n, int m, byte[] depth)
531
short tn2 = tree[n * 2];
532
short tm2 = tree[m * 2];
533
return (tn2 < tm2 || (tn2 == tm2 && ((sbyte)depth[n]) <= depth[m]));
536
// Scan a literal or distance tree to determine the frequencies of the codes
537
// in the bit length tree.
538
internal void Scan_tree(short[] tree, int max_code)
540
// the tree to be scanned
541
// and its largest code of non zero frequency
543
// iterates over all tree elements
545
// last emitted length
547
// length of current code
548
int nextlen = tree[0 * 2 + 1];
549
// length of next code
551
// repeat count of the current code
561
tree[(max_code + 1) * 2 + 1] = unchecked((short)(0xffff));
563
for (n = 0; n <= max_code; n++)
566
nextlen = tree[(n + 1) * 2 + 1];
567
if (++count < max_count && curlen == nextlen)
573
if (count < min_count)
575
bl_tree[curlen * 2] += (short)count;
581
if (curlen != prevlen)
583
bl_tree[curlen * 2]++;
585
bl_tree[REP_3_6 * 2]++;
591
bl_tree[REPZ_3_10 * 2]++;
595
bl_tree[REPZ_11_138 * 2]++;
609
if (curlen == nextlen)
623
// Construct the Huffman tree for the bit lengths and return the index in
624
// bl_order of the last bit length code to send.
625
internal int Build_bl_tree()
628
// index of last bit length code of non zero freq
629
// Determine the bit length frequencies for literal and distance trees
630
Scan_tree(dyn_ltree, l_desc.max_code);
631
Scan_tree(dyn_dtree, d_desc.max_code);
632
// Build the bit length tree:
633
bl_desc.Build_tree(this);
634
// opt_len now includes the length of the tree representations, except
635
// the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
636
// Determine the number of bit length codes to send. The pkzip format
637
// requires that at least 4 bit length codes be sent. (appnote.txt says
638
// 3 but the actual value used is 4.)
639
for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--)
641
if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] != 0)
646
// Update opt_len to include the bit length tree and counts
647
opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
651
// Send the header for a block using dynamic Huffman trees: the counts, the
652
// lengths of the bit length codes, the literal tree and the distance tree.
653
// IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
654
internal void Send_all_trees(int lcodes, int dcodes, int blcodes)
658
Send_bits(lcodes - 257, 5);
659
// not +255 as stated in appnote.txt
660
Send_bits(dcodes - 1, 5);
661
Send_bits(blcodes - 4, 4);
662
// not -3 as stated in appnote.txt
663
for (rank = 0; rank < blcodes; rank++)
665
Send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
667
Send_tree(dyn_ltree, lcodes - 1);
669
Send_tree(dyn_dtree, dcodes - 1);
673
// Send a literal or distance tree in compressed form, using the codes in
675
internal void Send_tree(short[] tree, int max_code)
677
// the tree to be sent
678
// and its largest code of non zero frequency
680
// iterates over all tree elements
682
// last emitted length
684
// length of current code
685
int nextlen = tree[0 * 2 + 1];
686
// length of next code
688
// repeat count of the current code
698
for (n = 0; n <= max_code; n++)
701
nextlen = tree[(n + 1) * 2 + 1];
702
if (++count < max_count && curlen == nextlen)
708
if (count < min_count)
712
Send_code(curlen, bl_tree);
714
while (--count != 0);
720
if (curlen != prevlen)
722
Send_code(curlen, bl_tree);
725
Send_code(REP_3_6, bl_tree);
726
Send_bits(count - 3, 2);
732
Send_code(REPZ_3_10, bl_tree);
733
Send_bits(count - 3, 3);
737
Send_code(REPZ_11_138, bl_tree);
738
Send_bits(count - 11, 7);
752
if (curlen == nextlen)
766
// Output a byte on the stream.
767
// IN assertion: there is enough room in pending_buf.
768
internal void Put_byte(byte[] p, int start, int len)
770
System.Array.Copy(p, start, pending_buf, pending, len);
774
internal void Put_byte(byte c)
776
pending_buf[pending++] = c;
779
internal void Put_short(int w)
781
Put_byte(unchecked((byte)(w)));
782
Put_byte(unchecked((byte)((int)(((uint)w) >> 8))));
785
internal void PutShortMSB(int b)
787
Put_byte(unchecked((byte)(b >> 8)));
788
Put_byte(unchecked((byte)(b)));
791
internal void Send_code(int c, short[] tree)
794
Send_bits((tree[c2] & unchecked((int)(0xffff))), (tree[c2 + 1] & unchecked((int)(
798
internal void Send_bits(int value, int length)
801
if (bi_valid > (int)Buf_size - len)
804
// bi_buf |= (val << bi_valid);
805
bi_buf |= (short)((val << bi_valid) & 0xffff);
807
bi_buf = (short)((int)(((uint)val) >> (Buf_size - bi_valid)));
808
bi_valid += len - Buf_size;
812
// bi_buf |= (value) << bi_valid;
813
bi_buf |= (short)((value << bi_valid) & 0xffff);
818
// Send one empty static block to give enough lookahead for inflate.
819
// This takes 10 bits, of which 7 may remain in the bit buffer.
820
// The current inflate code requires 9 bits of lookahead. If the
821
// last two codes for the previous block (real code plus EOB) were coded
822
// on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
823
// the last real code. In this case we send two empty static blocks instead
824
// of one. (There are no problems if the previous block is stored or fixed.)
825
// To simplify the code, we assume the worst case of last real code encoded
827
internal void _tr_align()
829
Send_bits(STATIC_TREES << 1, 3);
830
Send_code(END_BLOCK, StaticTree.static_ltree);
832
// Of the 10 bits for the empty block, we have already sent
833
// (10 - bi_valid) bits. The lookahead for the last real code (before
834
// the EOB of the previous block) was thus at least one plus the length
835
// of the EOB plus what we have just sent of the empty static block.
836
if (1 + last_eob_len + 10 - bi_valid < 9)
838
Send_bits(STATIC_TREES << 1, 3);
839
Send_code(END_BLOCK, StaticTree.static_ltree);
845
// Save the match info and tally the frequency counts. Return true if
846
// the current block must be flushed.
847
internal bool _tr_tally(int dist, int lc)
849
// distance of matched string
850
// match length-MIN_MATCH or unmatched char (if dist==0)
851
pending_buf[d_buf + last_lit * 2] = unchecked((byte)((int)(((uint)dist) >> 8)));
852
pending_buf[d_buf + last_lit * 2 + 1] = unchecked((byte)dist);
853
pending_buf[l_buf + last_lit] = unchecked((byte)lc);
857
// lc is the unmatched char
863
// Here, lc is the match length - MIN_MATCH
865
// dist = match distance - 1
866
dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
867
dyn_dtree[Tree.D_code(dist) * 2]++;
869
if ((last_lit & unchecked((int)(0x1fff))) == 0 && level > 2)
871
// Compute an upper bound for the compressed length
872
int out_length = last_lit * 8;
873
int in_length = strstart - block_start;
875
for (dcode = 0; dcode < D_CODES; dcode++)
877
out_length += (int)dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
879
out_length = (int)(((uint)out_length) >> 3);
880
if ((matches < (last_lit / 2)) && out_length < in_length / 2)
885
return (last_lit == lit_bufsize - 1);
888
// We avoid equality with lit_bufsize because of wraparound at 64K
889
// on 16 bit machines and because stored blocks are restricted to
891
// Send the block data compressed using the given Huffman trees
892
internal void Compress_block(short[] ltree, short[] dtree)
895
// distance of matched string
897
// match length or unmatched char (if dist == 0)
899
// running index in l_buf
903
// number of extra bits to send
908
dist = ((pending_buf[d_buf + lx * 2] << 8) & unchecked((int)(0xff00))) | (pending_buf
909
[d_buf + lx * 2 + 1] & unchecked((int)(0xff)));
910
lc = (pending_buf[l_buf + lx]) & unchecked((int)(0xff));
914
Send_code(lc, ltree);
918
// send a literal byte
919
// Here, lc is the match length - MIN_MATCH
920
code = Tree._length_code[lc];
921
Send_code(code + LITERALS + 1, ltree);
922
// send the length code
923
extra = Tree.extra_lbits[code];
926
lc -= Tree.base_length[code];
927
Send_bits(lc, extra);
929
// send the extra length bits
931
// dist is now the match distance - 1
932
code = Tree.D_code(dist);
933
Send_code(code, dtree);
934
// send the distance code
935
extra = Tree.extra_dbits[code];
938
dist -= Tree.base_dist[code];
939
Send_bits(dist, extra);
943
while (lx < last_lit);
945
// send the extra distance bits
946
// literal or match pair ?
947
// Check that the overlay between pending_buf and d_buf+l_buf is ok:
948
Send_code(END_BLOCK, ltree);
949
last_eob_len = ltree[END_BLOCK * 2 + 1];
952
// Set the data type to ASCII or BINARY, using a crude approximation:
953
// binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
954
// IN assertion: the fields freq of dyn_ltree are set and the total of all
955
// frequencies does not exceed 64K (to fit in an int on 16 bit machines).
956
internal void Set_data_type()
963
bin_freq += dyn_ltree[n * 2];
968
ascii_freq += dyn_ltree[n * 2];
973
bin_freq += dyn_ltree[n * 2];
976
data_type = unchecked((byte)(bin_freq > ((int)(((uint)ascii_freq) >> 2)) ? Z_BINARY
980
// Flush the bit buffer, keeping at most 7 bits in it.
981
internal void Bi_flush()
993
Put_byte(unchecked((byte)bi_buf));
994
bi_buf = (short)(((ushort)bi_buf) >> 8);
1000
// Flush the bit buffer and align the output on a byte boundary
1001
internal void Bi_windup()
1011
Put_byte(unchecked((byte)bi_buf));
1018
// Copy a stored block, storing first the length and its
1019
// one's complement if requested.
1020
internal void Copy_block(int buf, int len, bool header)
1024
// true if block header must be written
1027
// align on byte boundary
1029
// enough lookahead for inflate
1032
Put_short((short)len);
1033
Put_short((short)~len);
1035
// while(len--!=0) {
1036
// put_byte(window[buf+index]);
1039
Put_byte(window, buf, len);
1042
internal void Flush_block_only(bool eof)
1044
_tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
1045
block_start = strstart;
1046
strm.Flush_pending();
1049
// Copy without compression as much as possible from the input stream, return
1050
// the current block state.
1051
// This function does not insert new strings in the dictionary since
1052
// uncompressible data is probably not useful. This function is used
1053
// only for the level=0 compression option.
1054
// NOTE: this function should be optimized to avoid extra copying from
1055
// window to pending_buf.
1056
internal int Deflate_stored(int flush)
1058
// Stored blocks are limited to 0xffff bytes, pending_buf is limited
1059
// to pending_buf_size, and each stored block has a 5 byte header:
1060
int max_block_size = unchecked((int)(0xffff));
1062
if (max_block_size > pending_buf_size - 5)
1064
max_block_size = pending_buf_size - 5;
1066
// Copy as much as possible from input to output:
1069
// Fill the window as much as possible:
1073
if (lookahead == 0 && flush == Z_NO_FLUSH)
1082
// flush the current block
1083
strstart += lookahead;
1085
// Emit a stored block if pending_buf will be full:
1086
max_start = block_start + max_block_size;
1087
if (strstart == 0 || strstart >= max_start)
1089
// strstart == 0 is possible when wraparound on 16-bit machine
1090
lookahead = (int)(strstart - max_start);
1091
strstart = (int)max_start;
1092
Flush_block_only(false);
1093
if (strm.avail_out == 0)
1098
// Flush if we may have to slide, otherwise block_start may become
1099
// negative and the data will be gone:
1100
if (strstart - block_start >= w_size - MIN_LOOKAHEAD)
1102
Flush_block_only(false);
1103
if (strm.avail_out == 0)
1109
Flush_block_only(flush == Z_FINISH);
1110
if (strm.avail_out == 0)
1112
return (flush == Z_FINISH) ? FinishStarted : NeedMore;
1114
return flush == Z_FINISH ? FinishDone : BlockDone;
1117
// Send a stored block
1118
internal void _tr_stored_block(int buf, int stored_len, bool eof)
1121
// length of input block
1122
// true if this is the last block for a file
1123
Send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3);
1125
Copy_block(buf, stored_len, true);
1129
// Determine the best encoding for the current block: dynamic trees, static
1130
// trees or store, and output the encoded block to the zip file.
1131
internal void _tr_flush_block(int buf, int stored_len, bool eof)
1133
// input block, or NULL if too old
1134
// length of input block
1135
// true if this is the last block for a file
1138
// opt_len and static_len in bytes
1139
int max_blindex = 0;
1140
// index of last bit length code of non zero freq
1141
// Build the Huffman trees unless a stored block is forced
1144
// Check if the file is ascii or binary
1145
if (data_type == Z_UNKNOWN)
1149
// Construct the literal and distance trees
1150
l_desc.Build_tree(this);
1151
d_desc.Build_tree(this);
1152
// At this point, opt_len and static_len are the total bit lengths of
1153
// the compressed block data, excluding the tree representations.
1154
// Build the bit length tree for the above two trees, and get the index
1155
// in bl_order of the last bit length code to send.
1156
max_blindex = Build_bl_tree();
1157
// Determine the best encoding. Compute first the block length in bytes
1158
opt_lenb = (int)(((uint)(opt_len + 3 + 7)) >> 3);
1159
static_lenb = (int)(((uint)(static_len + 3 + 7)) >> 3);
1160
if (static_lenb <= opt_lenb)
1162
opt_lenb = static_lenb;
1167
opt_lenb = static_lenb = stored_len + 5;
1169
// force a stored block
1170
if (stored_len + 4 <= opt_lenb && buf != -1)
1172
// 4: two words for the lengths
1173
// The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
1174
// Otherwise we can't have processed more than WSIZE input bytes since
1175
// the last block flush, because compression would have been
1176
// successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
1177
// transform a block into a stored block.
1178
_tr_stored_block(buf, stored_len, eof);
1182
if (static_lenb == opt_lenb)
1184
Send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
1185
Compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
1189
Send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
1190
Send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
1191
Compress_block(dyn_ltree, dyn_dtree);
1194
// The above check is made mod 2^32, for files larger than 512 MB
1195
// and uLong implemented on 32 bits.
1203
// Fill the window when the lookahead becomes insufficient.
1204
// Updates strstart and lookahead.
1206
// IN assertion: lookahead < MIN_LOOKAHEAD
1207
// OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1208
// At least one byte has been read, or avail_in == 0; reads are
1209
// performed for at least two bytes (required for the zip translate_eol
1210
// option -- not supported here).
1211
internal void Fill_window()
1219
// Amount of free space at the end of the window.
1220
more = (window_size - lookahead - strstart);
1221
// Deal with !@#$% 64K limit:
1222
if (more == 0 && strstart == 0 && lookahead == 0)
1230
// Very unlikely, but possible on 16 bit machine if strstart == 0
1231
// and lookahead == 1 (input done one byte at time)
1236
// If the window is almost full and there is insufficient lookahead,
1237
// move the upper half to the lower one to make room in the upper half.
1238
if (strstart >= w_size + w_size - MIN_LOOKAHEAD)
1240
System.Array.Copy(window, w_size, window, 0, w_size);
1241
match_start -= w_size;
1243
// we now have strstart >= MAX_DIST
1244
block_start -= w_size;
1245
// Slide the hash table (could be avoided with 32 bit values
1246
// at the expense of memory usage). We slide even when level == 0
1247
// to keep the hash table consistent if we switch back to level > 0
1248
// later. (Using level 0 permanently is not an optimal usage of
1249
// zlib, so we don't care about this pathological case.)
1254
m = (head[--p] & unchecked((int)(0xffff)));
1255
head[p] = (m >= w_size ? (short)(m - w_size) : (short)0);
1262
m = (prev[--p] & unchecked((int)(0xffff)));
1263
prev[p] = (m >= w_size ? (short)(m - w_size) : (short)0);
1266
// If n is not on any hash chain, prev[n] is garbage but
1267
// its value will never be used.
1272
if (strm.avail_in == 0)
1276
// If there was no sliding:
1277
// strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1278
// more == window_size - lookahead - strstart
1279
// => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1280
// => more >= window_size - 2*WSIZE + 2
1281
// In the BIG_MEM or MMAP case (not yet supported),
1282
// window_size == input_size + MIN_LOOKAHEAD &&
1283
// strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1284
// Otherwise, window_size == 2*WSIZE so more >= 2.
1285
// If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1286
n = strm.Read_buf(window, strstart + lookahead, more);
1288
// Initialize the hash value now that we have some input:
1289
if (lookahead >= MIN_MATCH)
1291
ins_h = window[strstart] & unchecked((int)(0xff));
1292
ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & unchecked((int)(0xff))
1296
while (lookahead < MIN_LOOKAHEAD && strm.avail_in != 0);
1299
// If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1300
// but this is not important since only literal bytes will be emitted.
1301
// Compress as much as possible from the input stream, return the current
1303
// This function does not perform lazy evaluation of matches and inserts
1304
// new strings in the dictionary only for unmatched strings or for short
1305
// matches. It is used only for the fast compression options.
1306
internal int Deflate_fast(int flush)
1308
// short hash_head = 0; // head of the hash chain
1310
// head of the hash chain
1312
// set if current block must be flushed
1315
// Make sure that we always have enough lookahead, except
1316
// at the end of the input file. We need MAX_MATCH bytes
1317
// for the next match, plus MIN_MATCH bytes to insert the
1318
// string following the next match.
1319
if (lookahead < MIN_LOOKAHEAD)
1322
if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH)
1331
// flush the current block
1332
// Insert the string window[strstart .. strstart+2] in the
1333
// dictionary, and set hash_head to the head of the hash chain:
1334
if (lookahead >= MIN_MATCH)
1336
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & unchecked(
1337
(int)(0xff)))) & hash_mask;
1338
// prev[strstart&w_mask]=hash_head=head[ins_h];
1339
hash_head = (head[ins_h] & unchecked((int)(0xffff)));
1340
prev[strstart & w_mask] = head[ins_h];
1341
head[ins_h] = (short)strstart;
1343
// Find the longest match, discarding those <= prev_length.
1344
// At this point we have always match_length < MIN_MATCH
1345
if (hash_head != 0L && ((strstart - hash_head) & unchecked((int)(0xffff))) <= w_size
1348
// To simplify the code, we prevent matches with the string
1349
// of window index 0 (in particular we have to avoid a match
1350
// of the string with itself at the start of the input file).
1351
if (strategy != Z_HUFFMAN_ONLY)
1353
match_length = Longest_match(hash_head);
1356
// longest_match() sets match_start
1357
if (match_length >= MIN_MATCH)
1359
// check_match(strstart, match_start, match_length);
1360
bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
1361
lookahead -= match_length;
1362
// Insert new strings in the hash table only if the match length
1363
// is not too large. This saves time but degrades compression.
1364
if (match_length <= max_lazy_match && lookahead >= MIN_MATCH)
1369
// string at strstart already in hash table
1371
ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & unchecked(
1372
(int)(0xff)))) & hash_mask;
1373
// prev[strstart&w_mask]=hash_head=head[ins_h];
1374
hash_head = (head[ins_h] & unchecked((int)(0xffff)));
1375
prev[strstart & w_mask] = head[ins_h];
1376
head[ins_h] = (short)strstart;
1378
while (--match_length != 0);
1379
// strstart never exceeds WSIZE-MAX_MATCH, so there are
1380
// always MIN_MATCH bytes ahead.
1385
strstart += match_length;
1387
ins_h = window[strstart] & unchecked((int)(0xff));
1388
ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & unchecked((int)(0xff))
1394
// If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1395
// matter since it will be recomputed at next deflate call.
1396
// No match, output a literal byte
1397
bflush = _tr_tally(0, window[strstart] & unchecked((int)(0xff)));
1403
Flush_block_only(false);
1404
if (strm.avail_out == 0)
1410
Flush_block_only(flush == Z_FINISH);
1411
if (strm.avail_out == 0)
1413
if (flush == Z_FINISH)
1415
return FinishStarted;
1422
return flush == Z_FINISH ? FinishDone : BlockDone;
1425
// Same as above, but achieves better compression. We use a lazy
1426
// evaluation for matches: a match is finally adopted only if there is
1427
// no better match at the next window position.
1428
internal int Deflate_slow(int flush)
1430
// short hash_head = 0; // head of hash chain
1432
// head of hash chain
1434
// set if current block must be flushed
1435
// Process the input block.
1438
// Make sure that we always have enough lookahead, except
1439
// at the end of the input file. We need MAX_MATCH bytes
1440
// for the next match, plus MIN_MATCH bytes to insert the
1441
// string following the next match.
1442
if (lookahead < MIN_LOOKAHEAD)
1445
if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH)
1454
// flush the current block
1455
// Insert the string window[strstart .. strstart+2] in the
1456
// dictionary, and set hash_head to the head of the hash chain:
1457
if (lookahead >= MIN_MATCH)
1459
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & unchecked(
1460
(int)(0xff)))) & hash_mask;
1461
// prev[strstart&w_mask]=hash_head=head[ins_h];
1462
hash_head = (head[ins_h] & unchecked((int)(0xffff)));
1463
prev[strstart & w_mask] = head[ins_h];
1464
head[ins_h] = (short)strstart;
1466
// Find the longest match, discarding those <= prev_length.
1467
prev_length = match_length;
1468
prev_match = match_start;
1469
match_length = MIN_MATCH - 1;
1470
if (hash_head != 0 && prev_length < max_lazy_match && ((strstart - hash_head) & unchecked(
1471
(int)(0xffff))) <= w_size - MIN_LOOKAHEAD)
1473
// To simplify the code, we prevent matches with the string
1474
// of window index 0 (in particular we have to avoid a match
1475
// of the string with itself at the start of the input file).
1476
if (strategy != Z_HUFFMAN_ONLY)
1478
match_length = Longest_match(hash_head);
1480
// longest_match() sets match_start
1481
if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH &&
1482
strstart - match_start > 4096)))
1484
// If prev_match is also MIN_MATCH, match_start is garbage
1485
// but we will ignore the current match anyway.
1486
match_length = MIN_MATCH - 1;
1489
// If there was a match at the previous step and the current
1490
// match is not better, output the previous match:
1491
if (prev_length >= MIN_MATCH && match_length <= prev_length)
1493
int max_insert = strstart + lookahead - MIN_MATCH;
1494
// Do not insert strings in hash table beyond this.
1495
// check_match(strstart-1, prev_match, prev_length);
1496
bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
1497
// Insert in hash table all strings up to the end of the match.
1498
// strstart-1 and strstart are already inserted. If there is not
1499
// enough lookahead, the last two strings are not inserted in
1501
lookahead -= prev_length - 1;
1505
if (++strstart <= max_insert)
1507
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & unchecked(
1508
(int)(0xff)))) & hash_mask;
1509
//prev[strstart&w_mask]=hash_head=head[ins_h];
1510
hash_head = (head[ins_h] & unchecked((int)(0xffff)));
1511
prev[strstart & w_mask] = head[ins_h];
1512
head[ins_h] = (short)strstart;
1515
while (--prev_length != 0);
1516
match_available = 0;
1517
match_length = MIN_MATCH - 1;
1521
Flush_block_only(false);
1522
if (strm.avail_out == 0)
1530
if (match_available != 0)
1532
// If there was no match at the previous position, output a
1533
// single literal. If there was a match but the current match
1534
// is longer, truncate the previous match to a single literal.
1535
bflush = _tr_tally(0, window[strstart - 1] & unchecked((int)(0xff)));
1538
Flush_block_only(false);
1542
if (strm.avail_out == 0)
1549
// There is no previous match to compare with, wait for
1550
// the next step to decide.
1551
match_available = 1;
1557
if (match_available != 0)
1559
bflush = _tr_tally(0, window[strstart - 1] & unchecked((int)(0xff)));
1560
match_available = 0;
1562
Flush_block_only(flush == Z_FINISH);
1563
if (strm.avail_out == 0)
1565
if (flush == Z_FINISH)
1567
return FinishStarted;
1574
return flush == Z_FINISH ? FinishDone : BlockDone;
1577
internal int Longest_match(int cur_match)
1579
int chain_length = max_chain_length;
1580
// max hash chain length
1581
int scan = strstart;
1586
// length of current match
1587
int best_len = prev_length;
1588
// best match length so far
1589
int limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD
1591
int nice_match = this.nice_match;
1592
// Stop when cur_match becomes <= limit. To simplify the code,
1593
// we prevent matches with the string of window index 0.
1595
int strend = strstart + MAX_MATCH;
1596
byte scan_end1 = window[scan + best_len - 1];
1597
byte scan_end = window[scan + best_len];
1598
// The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1599
// It is easy to get rid of this optimization if necessary.
1600
// Do not waste too much time if we already have a good match:
1601
if (prev_length >= good_match)
1605
// Do not look for matches beyond the end of the input. This is necessary
1606
// to make deflate deterministic.
1607
if (nice_match > lookahead)
1609
nice_match = lookahead;
1614
// Skip to next match if the match length cannot increase
1615
// or if the match length is less than 2:
1616
if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1
1617
|| window[match] != window[scan] || window[++match] != window[scan + 1])
1621
// The check at best_len-1 can be removed because it will be made
1622
// again later. (This heuristic is not always a win.)
1623
// It is not necessary to compare scan[2] and match[2] since they
1624
// are always equal when the other bytes match, given that
1625
// the hash keys are equal and that HASH_BITS >= 8.
1631
while (window[++scan] == window[++match] && window[++scan] == window[++match] &&
1632
window[++scan] == window[++match] && window[++scan] == window[++match] && window
1633
[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan
1634
] == window[++match] && window[++scan] == window[++match] && scan < strend);
1635
// We check for insufficient lookahead only every 8th comparison;
1636
// the 256th check will be made at strstart+258.
1637
len = MAX_MATCH - (int)(strend - scan);
1638
scan = strend - MAX_MATCH;
1641
match_start = cur_match;
1643
if (len >= nice_match)
1647
scan_end1 = window[scan + best_len - 1];
1648
scan_end = window[scan + best_len];
1651
while ((cur_match = (prev[cur_match & wmask] & unchecked((int)(0xffff)))) > limit
1652
&& --chain_length != 0);
1653
if (best_len <= lookahead)
1660
internal int DeflateInit(ZStream strm, int level, int bits)
1662
return DeflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY
1666
internal int DeflateInit(ZStream strm, int level)
1668
return DeflateInit(strm, level, MAX_WBITS);
1671
internal int DeflateInit2(ZStream strm, int level, int method, int windowBits, int
1672
memLevel, int strategy)
1675
// byte[] my_version=ZLIB_VERSION;
1677
// if (version == null || version[0] != my_version[0]
1678
// || stream_size != sizeof(z_stream)) {
1679
// return Z_VERSION_ERROR;
1682
if (level == Z_DEFAULT_COMPRESSION)
1688
// undocumented feature: suppress zlib header
1690
windowBits = -windowBits;
1692
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits
1693
< 9 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy >
1696
return Z_STREAM_ERROR;
1698
strm.dstate = (Deflate)this;
1699
this.noheader = noheader;
1700
w_bits = windowBits;
1701
w_size = 1 << w_bits;
1702
w_mask = w_size - 1;
1703
hash_bits = memLevel + 7;
1704
hash_size = 1 << hash_bits;
1705
hash_mask = hash_size - 1;
1706
hash_shift = ((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
1707
window = new byte[w_size * 2];
1708
prev = new short[w_size];
1709
head = new short[hash_size];
1710
lit_bufsize = 1 << (memLevel + 6);
1711
// 16K elements by default
1712
// We overlay pending_buf and d_buf+l_buf. This works since the average
1713
// output size for (length,distance) codes is <= 24 bits.
1714
pending_buf = new byte[lit_bufsize * 4];
1715
pending_buf_size = lit_bufsize * 4;
1716
d_buf = lit_bufsize / 2;
1717
l_buf = (1 + 2) * lit_bufsize;
1719
//System.out.println("level="+level);
1720
this.strategy = strategy;
1721
this.method = unchecked((byte)method);
1722
return DeflateReset(strm);
1725
internal int DeflateReset(ZStream strm)
1727
strm.total_in = strm.total_out = 0;
1730
strm.data_type = Z_UNKNOWN;
1737
// was set to -1 by deflate(..., Z_FINISH);
1738
status = (noheader != 0) ? BUSY_STATE : INIT_STATE;
1739
strm.adler = strm._adler.Adler(0, null, 0, 0);
1740
last_flush = Z_NO_FLUSH;
1746
internal int DeflateEnd()
1748
if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE)
1750
return Z_STREAM_ERROR;
1752
// Deallocate in reverse order of allocations:
1759
return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1762
internal int DeflateParams(ZStream strm, int _level, int _strategy)
1765
if (_level == Z_DEFAULT_COMPRESSION)
1769
if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY)
1771
return Z_STREAM_ERROR;
1773
if (config_table[level].func != config_table[_level].func && strm.total_in != 0)
1775
// Flush the last buffer:
1776
err = strm.Deflate(Z_PARTIAL_FLUSH);
1778
if (level != _level)
1781
max_lazy_match = config_table[level].max_lazy;
1782
good_match = config_table[level].good_length;
1783
nice_match = config_table[level].nice_length;
1784
max_chain_length = config_table[level].max_chain;
1786
strategy = _strategy;
1790
internal int DeflateSetDictionary(ZStream strm, byte[] dictionary, int dictLength
1793
int length = dictLength;
1795
if (dictionary == null || status != INIT_STATE)
1797
return Z_STREAM_ERROR;
1799
strm.adler = strm._adler.Adler(strm.adler, dictionary, 0, dictLength);
1800
if (length < MIN_MATCH)
1804
if (length > w_size - MIN_LOOKAHEAD)
1806
length = w_size - MIN_LOOKAHEAD;
1807
index = dictLength - length;
1809
// use the tail of the dictionary
1810
System.Array.Copy(dictionary, index, window, 0, length);
1812
block_start = length;
1813
// Insert all strings in the hash table (except for the last two bytes).
1814
// s->lookahead stays null, so s->ins_h will be recomputed at the next
1815
// call of fill_window.
1816
ins_h = window[0] & unchecked((int)(0xff));
1817
ins_h = (((ins_h) << hash_shift) ^ (window[1] & unchecked((int)(0xff)))) & hash_mask;
1818
for (int n = 0; n <= length - MIN_MATCH; n++)
1820
ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & unchecked((int
1821
)(0xff)))) & hash_mask;
1822
prev[n & w_mask] = head[ins_h];
1823
head[ins_h] = (short)n;
1828
internal int DoDeflate(ZStream strm, int flush)
1831
if (flush > Z_FINISH || flush < 0)
1833
return Z_STREAM_ERROR;
1835
if (strm.next_out == null || (strm.next_in == null && strm.avail_in != 0) || (status
1836
== FINISH_STATE && flush != Z_FINISH))
1838
strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
1839
return Z_STREAM_ERROR;
1841
if (strm.avail_out == 0)
1843
strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
1848
old_flush = last_flush;
1850
// Write the zlib header
1851
if (status == INIT_STATE)
1853
int header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
1854
int level_flags = ((level - 1) & unchecked((int)(0xff))) >> 1;
1855
if (level_flags > 3)
1859
header |= (level_flags << 6);
1862
header |= PRESET_DICT;
1864
header += 31 - (header % 31);
1865
status = BUSY_STATE;
1866
PutShortMSB(header);
1867
// Save the adler32 of the preset dictionary:
1870
PutShortMSB((int)((long)(((ulong)strm.adler) >> 16)));
1871
PutShortMSB((int)(strm.adler & unchecked((int)(0xffff))));
1873
strm.adler = strm._adler.Adler(0, null, 0, 0);
1875
// Flush as much pending output as possible
1878
strm.Flush_pending();
1879
if (strm.avail_out == 0)
1881
//System.out.println(" avail_out==0");
1882
// Since avail_out is 0, deflate will be called again with
1883
// more output space, but possibly with both pending and
1884
// avail_in equal to zero. There won't be anything to do,
1885
// but this is not an error situation so make sure we
1886
// return OK instead of BUF_ERROR at next call of deflate:
1893
// Make sure there is something to do and avoid duplicate consecutive
1894
// flushes. For repeated and useless calls with Z_FINISH, we keep
1895
// returning Z_STREAM_END instead of Z_BUFF_ERROR.
1896
if (strm.avail_in == 0 && flush <= old_flush && flush != Z_FINISH)
1898
strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
1902
// User must not provide more input after the first FINISH:
1903
if (status == FINISH_STATE && strm.avail_in != 0)
1905
strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
1908
// Start a new block or continue the current one.
1909
if (strm.avail_in != 0 || lookahead != 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE
1913
switch (config_table[level].func)
1917
bstate = Deflate_stored(flush);
1923
bstate = Deflate_fast(flush);
1929
bstate = Deflate_slow(flush);
1938
if (bstate == FinishStarted || bstate == FinishDone)
1940
status = FINISH_STATE;
1942
if (bstate == NeedMore || bstate == FinishStarted)
1944
if (strm.avail_out == 0)
1948
// avoid BUF_ERROR next call, see above
1951
// If flush != Z_NO_FLUSH && avail_out == 0, the next call
1952
// of deflate should use the same flush parameter to make sure
1953
// that the flush is complete. So we don't have to output an
1954
// empty block here, this will be done at next call. This also
1955
// ensures that for a very small output buffer, we emit at most
1957
if (bstate == BlockDone)
1959
if (flush == Z_PARTIAL_FLUSH)
1965
// FULL_FLUSH or SYNC_FLUSH
1966
_tr_stored_block(0, 0, false);
1967
// For a full flush, this empty block will be recognized
1968
// as a special marker by inflate_sync().
1969
if (flush == Z_FULL_FLUSH)
1971
//state.head[s.hash_size-1]=0;
1972
for (int i = 0; i < hash_size; i++)
1979
strm.Flush_pending();
1980
if (strm.avail_out == 0)
1983
// avoid BUF_ERROR at next call, see above
1988
if (flush != Z_FINISH)
1994
return Z_STREAM_END;
1996
// Write the zlib trailer (adler32)
1997
PutShortMSB((int)((long)(((ulong)strm.adler) >> 16)));
1998
PutShortMSB((int)(strm.adler & unchecked((int)(0xffff))));
1999
strm.Flush_pending();
2000
// If avail_out is zero, the application will call deflate again
2001
// to flush the rest.
2003
// write the trailer only once!
2004
return pending != 0 ? Z_OK : Z_STREAM_END;