Deflate.cs 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  1. // Deflate.cs
  2. // ------------------------------------------------------------------
  3. //
  4. // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
  5. // All rights reserved.
  6. //
  7. // This code module is part of DotNetZip, a zipfile class library.
  8. //
  9. // ------------------------------------------------------------------
  10. //
  11. // This code is licensed under the Microsoft Public License.
  12. // See the file License.txt for the license details.
  13. // More info on: http://dotnetzip.codeplex.com
  14. //
  15. // ------------------------------------------------------------------
  16. //
  17. // last saved (in emacs):
  18. // Time-stamp: <2011-August-03 19:52:15>
  19. //
  20. // ------------------------------------------------------------------
  21. //
  22. // This module defines logic for handling the Deflate or compression.
  23. //
  24. // This code is based on multiple sources:
  25. // - the original zlib v1.2.3 source, which is Copyright (C) 1995-2005 Jean-loup Gailly.
  26. // - the original jzlib, which is Copyright (c) 2000-2003 ymnk, JCraft,Inc.
  27. //
  28. // However, this code is significantly different from both.
  29. // The object model is not the same, and many of the behaviors are different.
  30. //
  31. // In keeping with the license for these other works, the copyrights for
  32. // jzlib and zlib are here.
  33. //
  34. // -----------------------------------------------------------------------
  35. // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
  36. //
  37. // Redistribution and use in source and binary forms, with or without
  38. // modification, are permitted provided that the following conditions are met:
  39. //
  40. // 1. Redistributions of source code must retain the above copyright notice,
  41. // this list of conditions and the following disclaimer.
  42. //
  43. // 2. Redistributions in binary form must reproduce the above copyright
  44. // notice, this list of conditions and the following disclaimer in
  45. // the documentation and/or other materials provided with the distribution.
  46. //
  47. // 3. The names of the authors may not be used to endorse or promote products
  48. // derived from this software without specific prior written permission.
  49. //
  50. // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  51. // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  52. // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  53. // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  54. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  55. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  56. // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  57. // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  58. // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  59. // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  60. //
  61. // -----------------------------------------------------------------------
  62. //
  63. // This program is based on zlib-1.1.3; credit to authors
  64. // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  65. // and contributors of zlib.
  66. //
  67. // -----------------------------------------------------------------------
  68. using System;
  69. #pragma warning disable 0675
  70. namespace BestHTTP.Decompression.Zlib
  71. {
  72. internal enum BlockState
  73. {
  74. NeedMore = 0, // block not completed, need more input or more output
  75. BlockDone, // block flush performed
  76. FinishStarted, // finish started, need only more output at next deflate
  77. FinishDone // finish done, accept no more input or output
  78. }
  79. internal enum DeflateFlavor
  80. {
  81. Store,
  82. Fast,
  83. Slow
  84. }
  85. internal sealed class DeflateManager
  86. {
  87. private static readonly int MEM_LEVEL_MAX = 9;
  88. private static readonly int MEM_LEVEL_DEFAULT = 8;
  89. internal delegate BlockState CompressFunc(FlushType flush);
  90. internal class Config
  91. {
  92. // Use a faster search when the previous match is longer than this
  93. internal int GoodLength; // reduce lazy search above this match length
  94. // Attempt to find a better match only when the current match is
  95. // strictly smaller than this value. This mechanism is used only for
  96. // compression levels >= 4. For levels 1,2,3: MaxLazy is actually
  97. // MaxInsertLength. (See DeflateFast)
  98. internal int MaxLazy; // do not perform lazy search above this match length
  99. internal int NiceLength; // quit search above this match length
  100. // To speed up deflation, hash chains are never searched beyond this
  101. // length. A higher limit improves compression ratio but degrades the speed.
  102. internal int MaxChainLength;
  103. internal DeflateFlavor Flavor;
  104. private Config(int goodLength, int maxLazy, int niceLength, int maxChainLength, DeflateFlavor flavor)
  105. {
  106. this.GoodLength = goodLength;
  107. this.MaxLazy = maxLazy;
  108. this.NiceLength = niceLength;
  109. this.MaxChainLength = maxChainLength;
  110. this.Flavor = flavor;
  111. }
  112. public static Config Lookup(CompressionLevel level)
  113. {
  114. return Table[(int)level];
  115. }
  116. static Config()
  117. {
  118. Table = new Config[] {
  119. new Config(0, 0, 0, 0, DeflateFlavor.Store),
  120. new Config(4, 4, 8, 4, DeflateFlavor.Fast),
  121. new Config(4, 5, 16, 8, DeflateFlavor.Fast),
  122. new Config(4, 6, 32, 32, DeflateFlavor.Fast),
  123. new Config(4, 4, 16, 16, DeflateFlavor.Slow),
  124. new Config(8, 16, 32, 32, DeflateFlavor.Slow),
  125. new Config(8, 16, 128, 128, DeflateFlavor.Slow),
  126. new Config(8, 32, 128, 256, DeflateFlavor.Slow),
  127. new Config(32, 128, 258, 1024, DeflateFlavor.Slow),
  128. new Config(32, 258, 258, 4096, DeflateFlavor.Slow),
  129. };
  130. }
  131. private static readonly Config[] Table;
  132. }
  133. private CompressFunc DeflateFunction;
  134. private static readonly System.String[] _ErrorMessage = new System.String[]
  135. {
  136. "need dictionary",
  137. "stream end",
  138. "",
  139. "file error",
  140. "stream error",
  141. "data error",
  142. "insufficient memory",
  143. "buffer error",
  144. "incompatible version",
  145. ""
  146. };
  147. // preset dictionary flag in zlib header
  148. private static readonly int PRESET_DICT = 0x20;
  149. private static readonly int INIT_STATE = 42;
  150. private static readonly int BUSY_STATE = 113;
  151. private static readonly int FINISH_STATE = 666;
  152. // The deflate compression method
  153. private static readonly int Z_DEFLATED = 8;
  154. private static readonly int STORED_BLOCK = 0;
  155. private static readonly int STATIC_TREES = 1;
  156. private static readonly int DYN_TREES = 2;
  157. // The three kinds of block type
  158. private static readonly int Z_BINARY = 0;
  159. private static readonly int Z_ASCII = 1;
  160. private static readonly int Z_UNKNOWN = 2;
  161. private static readonly int Buf_size = 8 * 2;
  162. private static readonly int MIN_MATCH = 3;
  163. private static readonly int MAX_MATCH = 258;
  164. private static readonly int MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  165. private static readonly int HEAP_SIZE = (2 * InternalConstants.L_CODES + 1);
  166. private static readonly int END_BLOCK = 256;
  167. internal ZlibCodec _codec; // the zlib encoder/decoder
  168. internal int status; // as the name implies
  169. internal byte[] pending; // output still pending - waiting to be compressed
  170. internal int nextPending; // index of next pending byte to output to the stream
  171. internal int pendingCount; // number of bytes in the pending buffer
  172. internal sbyte data_type; // UNKNOWN, BINARY or ASCII
  173. internal int last_flush; // value of flush param for previous deflate call
  174. internal int w_size; // LZ77 window size (32K by default)
  175. internal int w_bits; // log2(w_size) (8..16)
  176. internal int w_mask; // w_size - 1
  177. //internal byte[] dictionary;
  178. internal byte[] window;
  179. // Sliding window. Input bytes are read into the second half of the window,
  180. // and move to the first half later to keep a dictionary of at least wSize
  181. // bytes. With this organization, matches are limited to a distance of
  182. // wSize-MAX_MATCH bytes, but this ensures that IO is always
  183. // performed with a length multiple of the block size.
  184. //
  185. // To do: use the user input buffer as sliding window.
  186. internal int window_size;
  187. // Actual size of window: 2*wSize, except when the user input buffer
  188. // is directly used as sliding window.
  189. internal short[] prev;
  190. // Link to older string with same hash index. To limit the size of this
  191. // array to 64K, this link is maintained only for the last 32K strings.
  192. // An index in this array is thus a window index modulo 32K.
  193. internal short[] head; // Heads of the hash chains or NIL.
  194. internal int ins_h; // hash index of string to be inserted
  195. internal int hash_size; // number of elements in hash table
  196. internal int hash_bits; // log2(hash_size)
  197. internal int hash_mask; // hash_size-1
  198. // Number of bits by which ins_h must be shifted at each input
  199. // step. It must be such that after MIN_MATCH steps, the oldest
  200. // byte no longer takes part in the hash key, that is:
  201. // hash_shift * MIN_MATCH >= hash_bits
  202. internal int hash_shift;
  203. // Window position at the beginning of the current output block. Gets
  204. // negative when the window is moved backwards.
  205. internal int block_start;
  206. Config config;
  207. internal int match_length; // length of best match
  208. internal int prev_match; // previous match
  209. internal int match_available; // set if previous match exists
  210. internal int strstart; // start of string to insert into.....????
  211. internal int match_start; // start of matching string
  212. internal int lookahead; // number of valid bytes ahead in window
  213. // Length of the best match at previous step. Matches not greater than this
  214. // are discarded. This is used in the lazy match evaluation.
  215. internal int prev_length;
  216. // Insert new strings in the hash table only if the match length is not
  217. // greater than this length. This saves time but degrades compression.
  218. // max_insert_length is used only for compression levels <= 3.
  219. internal CompressionLevel compressionLevel; // compression level (1..9)
  220. internal CompressionStrategy compressionStrategy; // favor or force Huffman coding
  221. internal short[] dyn_ltree; // literal and length tree
  222. internal short[] dyn_dtree; // distance tree
  223. internal short[] bl_tree; // Huffman tree for bit lengths
  224. internal ZTree treeLiterals = new ZTree(); // desc for literal tree
  225. internal ZTree treeDistances = new ZTree(); // desc for distance tree
  226. internal ZTree treeBitLengths = new ZTree(); // desc for bit length tree
  227. // number of codes at each bit length for an optimal tree
  228. internal short[] bl_count = new short[InternalConstants.MAX_BITS + 1];
  229. // heap used to build the Huffman trees
  230. internal int[] heap = new int[2 * InternalConstants.L_CODES + 1];
  231. internal int heap_len; // number of elements in the heap
  232. internal int heap_max; // element of largest frequency
  233. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  234. // The same heap array is used to build all trees.
  235. // Depth of each subtree used as tie breaker for trees of equal frequency
  236. internal sbyte[] depth = new sbyte[2 * InternalConstants.L_CODES + 1];
  237. internal int _lengthOffset; // index for literals or lengths
  238. // Size of match buffer for literals/lengths. There are 4 reasons for
  239. // limiting lit_bufsize to 64K:
  240. // - frequencies can be kept in 16 bit counters
  241. // - if compression is not successful for the first block, all input
  242. // data is still in the window so we can still emit a stored block even
  243. // when input comes from standard input. (This can also be done for
  244. // all blocks if lit_bufsize is not greater than 32K.)
  245. // - if compression is not successful for a file smaller than 64K, we can
  246. // even emit a stored file instead of a stored block (saving 5 bytes).
  247. // This is applicable only for zip (not gzip or zlib).
  248. // - creating new Huffman trees less frequently may not provide fast
  249. // adaptation to changes in the input data statistics. (Take for
  250. // example a binary file with poorly compressible code followed by
  251. // a highly compressible string table.) Smaller buffer sizes give
  252. // fast adaptation but have of course the overhead of transmitting
  253. // trees more frequently.
  254. internal int lit_bufsize;
  255. internal int last_lit; // running index in l_buf
  256. // Buffer for distances. To simplify the code, d_buf and l_buf have
  257. // the same number of elements. To use different lengths, an extra flag
  258. // array would be necessary.
  259. internal int _distanceOffset; // index into pending; points to distance data??
  260. internal int opt_len; // bit length of current block with optimal trees
  261. internal int static_len; // bit length of current block with static trees
  262. internal int matches; // number of string matches in current block
  263. internal int last_eob_len; // bit length of EOB code for last block
  264. // Output buffer. bits are inserted starting at the bottom (least
  265. // significant bits).
  266. internal short bi_buf;
  267. // Number of valid bits in bi_buf. All bits above the last valid bit
  268. // are always zero.
  269. internal int bi_valid;
  270. internal DeflateManager()
  271. {
  272. dyn_ltree = new short[HEAP_SIZE * 2];
  273. dyn_dtree = new short[(2 * InternalConstants.D_CODES + 1) * 2]; // distance tree
  274. bl_tree = new short[(2 * InternalConstants.BL_CODES + 1) * 2]; // Huffman tree for bit lengths
  275. }
  276. // lm_init
  277. private void _InitializeLazyMatch()
  278. {
  279. window_size = 2 * w_size;
  280. // clear the hash - workitem 9063
  281. Array.Clear(head, 0, hash_size);
  282. //for (int i = 0; i < hash_size; i++) head[i] = 0;
  283. config = Config.Lookup(compressionLevel);
  284. SetDeflater();
  285. strstart = 0;
  286. block_start = 0;
  287. lookahead = 0;
  288. match_length = prev_length = MIN_MATCH - 1;
  289. match_available = 0;
  290. ins_h = 0;
  291. }
  292. // Initialize the tree data structures for a new zlib stream.
  293. private void _InitializeTreeData()
  294. {
  295. treeLiterals.dyn_tree = dyn_ltree;
  296. treeLiterals.staticTree = StaticTree.Literals;
  297. treeDistances.dyn_tree = dyn_dtree;
  298. treeDistances.staticTree = StaticTree.Distances;
  299. treeBitLengths.dyn_tree = bl_tree;
  300. treeBitLengths.staticTree = StaticTree.BitLengths;
  301. bi_buf = 0;
  302. bi_valid = 0;
  303. last_eob_len = 8; // enough lookahead for inflate
  304. // Initialize the first block of the first file:
  305. _InitializeBlocks();
  306. }
  307. internal void _InitializeBlocks()
  308. {
  309. // Initialize the trees.
  310. for (int i = 0; i < InternalConstants.L_CODES; i++)
  311. dyn_ltree[i * 2] = 0;
  312. for (int i = 0; i < InternalConstants.D_CODES; i++)
  313. dyn_dtree[i * 2] = 0;
  314. for (int i = 0; i < InternalConstants.BL_CODES; i++)
  315. bl_tree[i * 2] = 0;
  316. dyn_ltree[END_BLOCK * 2] = 1;
  317. opt_len = static_len = 0;
  318. last_lit = matches = 0;
  319. }
  320. // Restore the heap property by moving down the tree starting at node k,
  321. // exchanging a node with the smallest of its two sons if necessary, stopping
  322. // when the heap property is re-established (each father smaller than its
  323. // two sons).
  324. internal void pqdownheap(short[] tree, int k)
  325. {
  326. int v = heap[k];
  327. int j = k << 1; // left son of k
  328. while (j <= heap_len)
  329. {
  330. // Set j to the smallest of the two sons:
  331. if (j < heap_len && _IsSmaller(tree, heap[j + 1], heap[j], depth))
  332. {
  333. j++;
  334. }
  335. // Exit if v is smaller than both sons
  336. if (_IsSmaller(tree, v, heap[j], depth))
  337. break;
  338. // Exchange v with the smallest son
  339. heap[k] = heap[j]; k = j;
  340. // And continue down the tree, setting j to the left son of k
  341. j <<= 1;
  342. }
  343. heap[k] = v;
  344. }
  345. internal static bool _IsSmaller(short[] tree, int n, int m, sbyte[] depth)
  346. {
  347. short tn2 = tree[n * 2];
  348. short tm2 = tree[m * 2];
  349. return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
  350. }
  351. // Scan a literal or distance tree to determine the frequencies of the codes
  352. // in the bit length tree.
  353. internal void scan_tree(short[] tree, int max_code)
  354. {
  355. int n; // iterates over all tree elements
  356. int prevlen = -1; // last emitted length
  357. int curlen; // length of current code
  358. int nextlen = (int)tree[0 * 2 + 1]; // length of next code
  359. int count = 0; // repeat count of the current code
  360. int max_count = 7; // max repeat count
  361. int min_count = 4; // min repeat count
  362. if (nextlen == 0)
  363. {
  364. max_count = 138; min_count = 3;
  365. }
  366. tree[(max_code + 1) * 2 + 1] = (short)0x7fff; // guard //??
  367. for (n = 0; n <= max_code; n++)
  368. {
  369. curlen = nextlen; nextlen = (int)tree[(n + 1) * 2 + 1];
  370. if (++count < max_count && curlen == nextlen)
  371. {
  372. continue;
  373. }
  374. else if (count < min_count)
  375. {
  376. bl_tree[curlen * 2] = (short)(bl_tree[curlen * 2] + count);
  377. }
  378. else if (curlen != 0)
  379. {
  380. if (curlen != prevlen)
  381. bl_tree[curlen * 2]++;
  382. bl_tree[InternalConstants.REP_3_6 * 2]++;
  383. }
  384. else if (count <= 10)
  385. {
  386. bl_tree[InternalConstants.REPZ_3_10 * 2]++;
  387. }
  388. else
  389. {
  390. bl_tree[InternalConstants.REPZ_11_138 * 2]++;
  391. }
  392. count = 0; prevlen = curlen;
  393. if (nextlen == 0)
  394. {
  395. max_count = 138; min_count = 3;
  396. }
  397. else if (curlen == nextlen)
  398. {
  399. max_count = 6; min_count = 3;
  400. }
  401. else
  402. {
  403. max_count = 7; min_count = 4;
  404. }
  405. }
  406. }
  407. // Construct the Huffman tree for the bit lengths and return the index in
  408. // bl_order of the last bit length code to send.
  409. internal int build_bl_tree()
  410. {
  411. int max_blindex; // index of last bit length code of non zero freq
  412. // Determine the bit length frequencies for literal and distance trees
  413. scan_tree(dyn_ltree, treeLiterals.max_code);
  414. scan_tree(dyn_dtree, treeDistances.max_code);
  415. // Build the bit length tree:
  416. treeBitLengths.build_tree(this);
  417. // opt_len now includes the length of the tree representations, except
  418. // the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  419. // Determine the number of bit length codes to send. The pkzip format
  420. // requires that at least 4 bit length codes be sent. (appnote.txt says
  421. // 3 but the actual value used is 4.)
  422. for (max_blindex = InternalConstants.BL_CODES - 1; max_blindex >= 3; max_blindex--)
  423. {
  424. if (bl_tree[ZTree.bl_order[max_blindex] * 2 + 1] != 0)
  425. break;
  426. }
  427. // Update opt_len to include the bit length tree and counts
  428. opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  429. return max_blindex;
  430. }
  431. // Send the header for a block using dynamic Huffman trees: the counts, the
  432. // lengths of the bit length codes, the literal tree and the distance tree.
  433. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  434. internal void send_all_trees(int lcodes, int dcodes, int blcodes)
  435. {
  436. int rank; // index in bl_order
  437. send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  438. send_bits(dcodes - 1, 5);
  439. send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  440. for (rank = 0; rank < blcodes; rank++)
  441. {
  442. send_bits(bl_tree[ZTree.bl_order[rank] * 2 + 1], 3);
  443. }
  444. send_tree(dyn_ltree, lcodes - 1); // literal tree
  445. send_tree(dyn_dtree, dcodes - 1); // distance tree
  446. }
  447. // Send a literal or distance tree in compressed form, using the codes in
  448. // bl_tree.
  449. internal void send_tree(short[] tree, int max_code)
  450. {
  451. int n; // iterates over all tree elements
  452. int prevlen = -1; // last emitted length
  453. int curlen; // length of current code
  454. int nextlen = tree[0 * 2 + 1]; // length of next code
  455. int count = 0; // repeat count of the current code
  456. int max_count = 7; // max repeat count
  457. int min_count = 4; // min repeat count
  458. if (nextlen == 0)
  459. {
  460. max_count = 138; min_count = 3;
  461. }
  462. for (n = 0; n <= max_code; n++)
  463. {
  464. curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1];
  465. if (++count < max_count && curlen == nextlen)
  466. {
  467. continue;
  468. }
  469. else if (count < min_count)
  470. {
  471. do
  472. {
  473. send_code(curlen, bl_tree);
  474. }
  475. while (--count != 0);
  476. }
  477. else if (curlen != 0)
  478. {
  479. if (curlen != prevlen)
  480. {
  481. send_code(curlen, bl_tree); count--;
  482. }
  483. send_code(InternalConstants.REP_3_6, bl_tree);
  484. send_bits(count - 3, 2);
  485. }
  486. else if (count <= 10)
  487. {
  488. send_code(InternalConstants.REPZ_3_10, bl_tree);
  489. send_bits(count - 3, 3);
  490. }
  491. else
  492. {
  493. send_code(InternalConstants.REPZ_11_138, bl_tree);
  494. send_bits(count - 11, 7);
  495. }
  496. count = 0; prevlen = curlen;
  497. if (nextlen == 0)
  498. {
  499. max_count = 138; min_count = 3;
  500. }
  501. else if (curlen == nextlen)
  502. {
  503. max_count = 6; min_count = 3;
  504. }
  505. else
  506. {
  507. max_count = 7; min_count = 4;
  508. }
  509. }
  510. }
  511. // Output a block of bytes on the stream.
  512. // IN assertion: there is enough room in pending_buf.
  513. private void put_bytes(byte[] p, int start, int len)
  514. {
  515. Array.Copy(p, start, pending, pendingCount, len);
  516. pendingCount += len;
  517. }
  518. #if NOTNEEDED
  519. private void put_byte(byte c)
  520. {
  521. pending[pendingCount++] = c;
  522. }
  523. internal void put_short(int b)
  524. {
  525. unchecked
  526. {
  527. pending[pendingCount++] = (byte)b;
  528. pending[pendingCount++] = (byte)(b >> 8);
  529. }
  530. }
  531. internal void putShortMSB(int b)
  532. {
  533. unchecked
  534. {
  535. pending[pendingCount++] = (byte)(b >> 8);
  536. pending[pendingCount++] = (byte)b;
  537. }
  538. }
  539. #endif
  540. internal void send_code(int c, short[] tree)
  541. {
  542. int c2 = c * 2;
  543. send_bits((tree[c2] & 0xffff), (tree[c2 + 1] & 0xffff));
  544. }
  545. internal void send_bits(int value, int length)
  546. {
  547. int len = length;
  548. unchecked
  549. {
  550. if (bi_valid > (int)Buf_size - len)
  551. {
  552. //int val = value;
  553. // bi_buf |= (val << bi_valid);
  554. bi_buf |= (short)((value << bi_valid) & 0xffff);
  555. //put_short(bi_buf);
  556. pending[pendingCount++] = (byte)bi_buf;
  557. pending[pendingCount++] = (byte)(bi_buf >> 8);
  558. bi_buf = (short)((uint)value >> (Buf_size - bi_valid));
  559. bi_valid += len - Buf_size;
  560. }
  561. else
  562. {
  563. // bi_buf |= (value) << bi_valid;
  564. bi_buf |= (short)((value << bi_valid) & 0xffff);
  565. bi_valid += len;
  566. }
  567. }
  568. }
  569. // Send one empty static block to give enough lookahead for inflate.
  570. // This takes 10 bits, of which 7 may remain in the bit buffer.
  571. // The current inflate code requires 9 bits of lookahead. If the
  572. // last two codes for the previous block (real code plus EOB) were coded
  573. // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  574. // the last real code. In this case we send two empty static blocks instead
  575. // of one. (There are no problems if the previous block is stored or fixed.)
  576. // To simplify the code, we assume the worst case of last real code encoded
  577. // on one bit only.
  578. internal void _tr_align()
  579. {
  580. send_bits(STATIC_TREES << 1, 3);
  581. send_code(END_BLOCK, StaticTree.lengthAndLiteralsTreeCodes);
  582. bi_flush();
  583. // Of the 10 bits for the empty block, we have already sent
  584. // (10 - bi_valid) bits. The lookahead for the last real code (before
  585. // the EOB of the previous block) was thus at least one plus the length
  586. // of the EOB plus what we have just sent of the empty static block.
  587. if (1 + last_eob_len + 10 - bi_valid < 9)
  588. {
  589. send_bits(STATIC_TREES << 1, 3);
  590. send_code(END_BLOCK, StaticTree.lengthAndLiteralsTreeCodes);
  591. bi_flush();
  592. }
  593. last_eob_len = 7;
  594. }
  595. // Save the match info and tally the frequency counts. Return true if
  596. // the current block must be flushed.
  597. internal bool _tr_tally(int dist, int lc)
  598. {
  599. pending[_distanceOffset + last_lit * 2] = unchecked((byte) ( (uint)dist >> 8 ) );
  600. pending[_distanceOffset + last_lit * 2 + 1] = unchecked((byte)dist);
  601. pending[_lengthOffset + last_lit] = unchecked((byte)lc);
  602. last_lit++;
  603. if (dist == 0)
  604. {
  605. // lc is the unmatched char
  606. dyn_ltree[lc * 2]++;
  607. }
  608. else
  609. {
  610. matches++;
  611. // Here, lc is the match length - MIN_MATCH
  612. dist--; // dist = match distance - 1
  613. dyn_ltree[(ZTree.LengthCode[lc] + InternalConstants.LITERALS + 1) * 2]++;
  614. dyn_dtree[ZTree.DistanceCode(dist) * 2]++;
  615. }
  616. if ((last_lit & 0x1fff) == 0 && (int)compressionLevel > 2)
  617. {
  618. // Compute an upper bound for the compressed length
  619. int out_length = last_lit << 3;
  620. int in_length = strstart - block_start;
  621. int dcode;
  622. for (dcode = 0; dcode < InternalConstants.D_CODES; dcode++)
  623. {
  624. out_length = (int)(out_length + (int)dyn_dtree[dcode * 2] * (5L + ZTree.ExtraDistanceBits[dcode]));
  625. }
  626. out_length >>= 3;
  627. if ((matches < (last_lit / 2)) && out_length < in_length / 2)
  628. return true;
  629. }
  630. return (last_lit == lit_bufsize - 1) || (last_lit == lit_bufsize);
  631. // dinoch - wraparound?
  632. // We avoid equality with lit_bufsize because of wraparound at 64K
  633. // on 16 bit machines and because stored blocks are restricted to
  634. // 64K-1 bytes.
  635. }
  636. // Send the block data compressed using the given Huffman trees
  637. internal void send_compressed_block(short[] ltree, short[] dtree)
  638. {
  639. int distance; // distance of matched string
  640. int lc; // match length or unmatched char (if dist == 0)
  641. int lx = 0; // running index in l_buf
  642. int code; // the code to send
  643. int extra; // number of extra bits to send
  644. if (last_lit != 0)
  645. {
  646. do
  647. {
  648. int ix = _distanceOffset + lx * 2;
  649. distance = ((pending[ix] << 8) & 0xff00) |
  650. (pending[ix + 1] & 0xff);
  651. lc = (pending[_lengthOffset + lx]) & 0xff;
  652. lx++;
  653. if (distance == 0)
  654. {
  655. send_code(lc, ltree); // send a literal byte
  656. }
  657. else
  658. {
  659. // literal or match pair
  660. // Here, lc is the match length - MIN_MATCH
  661. code = ZTree.LengthCode[lc];
  662. // send the length code
  663. send_code(code + InternalConstants.LITERALS + 1, ltree);
  664. extra = ZTree.ExtraLengthBits[code];
  665. if (extra != 0)
  666. {
  667. // send the extra length bits
  668. lc -= ZTree.LengthBase[code];
  669. send_bits(lc, extra);
  670. }
  671. distance--; // dist is now the match distance - 1
  672. code = ZTree.DistanceCode(distance);
  673. // send the distance code
  674. send_code(code, dtree);
  675. extra = ZTree.ExtraDistanceBits[code];
  676. if (extra != 0)
  677. {
  678. // send the extra distance bits
  679. distance -= ZTree.DistanceBase[code];
  680. send_bits(distance, extra);
  681. }
  682. }
  683. // Check that the overlay between pending and d_buf+l_buf is ok:
  684. }
  685. while (lx < last_lit);
  686. }
  687. send_code(END_BLOCK, ltree);
  688. last_eob_len = ltree[END_BLOCK * 2 + 1];
  689. }
  690. // Set the data type to ASCII or BINARY, using a crude approximation:
  691. // binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
  692. // IN assertion: the fields freq of dyn_ltree are set and the total of all
  693. // frequencies does not exceed 64K (to fit in an int on 16 bit machines).
  694. internal void set_data_type()
  695. {
  696. int n = 0;
  697. int ascii_freq = 0;
  698. int bin_freq = 0;
  699. while (n < 7)
  700. {
  701. bin_freq += dyn_ltree[n * 2]; n++;
  702. }
  703. while (n < 128)
  704. {
  705. ascii_freq += dyn_ltree[n * 2]; n++;
  706. }
  707. while (n < InternalConstants.LITERALS)
  708. {
  709. bin_freq += dyn_ltree[n * 2]; n++;
  710. }
  711. data_type = (sbyte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII);
  712. }
  713. // Flush the bit buffer, keeping at most 7 bits in it.
  714. internal void bi_flush()
  715. {
  716. if (bi_valid == 16)
  717. {
  718. pending[pendingCount++] = (byte)bi_buf;
  719. pending[pendingCount++] = (byte)(bi_buf >> 8);
  720. bi_buf = 0;
  721. bi_valid = 0;
  722. }
  723. else if (bi_valid >= 8)
  724. {
  725. //put_byte((byte)bi_buf);
  726. pending[pendingCount++] = (byte)bi_buf;
  727. bi_buf >>= 8;
  728. bi_valid -= 8;
  729. }
  730. }
  731. // Flush the bit buffer and align the output on a byte boundary
  732. internal void bi_windup()
  733. {
  734. if (bi_valid > 8)
  735. {
  736. pending[pendingCount++] = (byte)bi_buf;
  737. pending[pendingCount++] = (byte)(bi_buf >> 8);
  738. }
  739. else if (bi_valid > 0)
  740. {
  741. //put_byte((byte)bi_buf);
  742. pending[pendingCount++] = (byte)bi_buf;
  743. }
  744. bi_buf = 0;
  745. bi_valid = 0;
  746. }
  747. // Copy a stored block, storing first the length and its
  748. // one's complement if requested.
  749. internal void copy_block(int buf, int len, bool header)
  750. {
  751. bi_windup(); // align on byte boundary
  752. last_eob_len = 8; // enough lookahead for inflate
  753. if (header)
  754. unchecked
  755. {
  756. //put_short((short)len);
  757. pending[pendingCount++] = (byte)len;
  758. pending[pendingCount++] = (byte)(len >> 8);
  759. //put_short((short)~len);
  760. pending[pendingCount++] = (byte)~len;
  761. pending[pendingCount++] = (byte)(~len >> 8);
  762. }
  763. put_bytes(window, buf, len);
  764. }
  765. internal void flush_block_only(bool eof)
  766. {
  767. _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
  768. block_start = strstart;
  769. _codec.flush_pending();
  770. }
  771. // Copy without compression as much as possible from the input stream, return
  772. // the current block state.
  773. // This function does not insert new strings in the dictionary since
  774. // uncompressible data is probably not useful. This function is used
  775. // only for the level=0 compression option.
  776. // NOTE: this function should be optimized to avoid extra copying from
  777. // window to pending_buf.
  778. internal BlockState DeflateNone(FlushType flush)
  779. {
  780. // Stored blocks are limited to 0xffff bytes, pending is limited
  781. // to pending_buf_size, and each stored block has a 5 byte header:
  782. int max_block_size = 0xffff;
  783. int max_start;
  784. if (max_block_size > pending.Length - 5)
  785. {
  786. max_block_size = pending.Length - 5;
  787. }
  788. // Copy as much as possible from input to output:
  789. while (true)
  790. {
  791. // Fill the window as much as possible:
  792. if (lookahead <= 1)
  793. {
  794. _fillWindow();
  795. if (lookahead == 0 && flush == FlushType.None)
  796. return BlockState.NeedMore;
  797. if (lookahead == 0)
  798. break; // flush the current block
  799. }
  800. strstart += lookahead;
  801. lookahead = 0;
  802. // Emit a stored block if pending will be full:
  803. max_start = block_start + max_block_size;
  804. if (strstart == 0 || strstart >= max_start)
  805. {
  806. // strstart == 0 is possible when wraparound on 16-bit machine
  807. lookahead = (int)(strstart - max_start);
  808. strstart = (int)max_start;
  809. flush_block_only(false);
  810. if (_codec.AvailableBytesOut == 0)
  811. return BlockState.NeedMore;
  812. }
  813. // Flush if we may have to slide, otherwise block_start may become
  814. // negative and the data will be gone:
  815. if (strstart - block_start >= w_size - MIN_LOOKAHEAD)
  816. {
  817. flush_block_only(false);
  818. if (_codec.AvailableBytesOut == 0)
  819. return BlockState.NeedMore;
  820. }
  821. }
  822. flush_block_only(flush == FlushType.Finish);
  823. if (_codec.AvailableBytesOut == 0)
  824. return (flush == FlushType.Finish) ? BlockState.FinishStarted : BlockState.NeedMore;
  825. return flush == FlushType.Finish ? BlockState.FinishDone : BlockState.BlockDone;
  826. }
  827. // Send a stored block
  828. internal void _tr_stored_block(int buf, int stored_len, bool eof)
  829. {
  830. send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
  831. copy_block(buf, stored_len, true); // with header
  832. }
  833. // Determine the best encoding for the current block: dynamic trees, static
  834. // trees or store, and output the encoded block to the zip file.
  835. internal void _tr_flush_block(int buf, int stored_len, bool eof)
  836. {
  837. int opt_lenb, static_lenb; // opt_len and static_len in bytes
  838. int max_blindex = 0; // index of last bit length code of non zero freq
  839. // Build the Huffman trees unless a stored block is forced
  840. if (compressionLevel > 0)
  841. {
  842. // Check if the file is ascii or binary
  843. if (data_type == Z_UNKNOWN)
  844. set_data_type();
  845. // Construct the literal and distance trees
  846. treeLiterals.build_tree(this);
  847. treeDistances.build_tree(this);
  848. // At this point, opt_len and static_len are the total bit lengths of
  849. // the compressed block data, excluding the tree representations.
  850. // Build the bit length tree for the above two trees, and get the index
  851. // in bl_order of the last bit length code to send.
  852. max_blindex = build_bl_tree();
  853. // Determine the best encoding. Compute first the block length in bytes
  854. opt_lenb = (opt_len + 3 + 7) >> 3;
  855. static_lenb = (static_len + 3 + 7) >> 3;
  856. if (static_lenb <= opt_lenb)
  857. opt_lenb = static_lenb;
  858. }
  859. else
  860. {
  861. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  862. }
  863. if (stored_len + 4 <= opt_lenb && buf != -1)
  864. {
  865. // 4: two words for the lengths
  866. // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  867. // Otherwise we can't have processed more than WSIZE input bytes since
  868. // the last block flush, because compression would have been
  869. // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  870. // transform a block into a stored block.
  871. _tr_stored_block(buf, stored_len, eof);
  872. }
  873. else if (static_lenb == opt_lenb)
  874. {
  875. send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
  876. send_compressed_block(StaticTree.lengthAndLiteralsTreeCodes, StaticTree.distTreeCodes);
  877. }
  878. else
  879. {
  880. send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
  881. send_all_trees(treeLiterals.max_code + 1, treeDistances.max_code + 1, max_blindex + 1);
  882. send_compressed_block(dyn_ltree, dyn_dtree);
  883. }
  884. // The above check is made mod 2^32, for files larger than 512 MB
  885. // and uLong implemented on 32 bits.
  886. _InitializeBlocks();
  887. if (eof)
  888. {
  889. bi_windup();
  890. }
  891. }
  892. // Fill the window when the lookahead becomes insufficient.
  893. // Updates strstart and lookahead.
  894. //
  895. // IN assertion: lookahead < MIN_LOOKAHEAD
  896. // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  897. // At least one byte has been read, or avail_in == 0; reads are
  898. // performed for at least two bytes (required for the zip translate_eol
  899. // option -- not supported here).
  900. private void _fillWindow()
  901. {
  902. int n, m;
  903. int p;
  904. int more; // Amount of free space at the end of the window.
  905. do
  906. {
  907. more = (window_size - lookahead - strstart);
  908. // Deal with !@#$% 64K limit:
  909. if (more == 0 && strstart == 0 && lookahead == 0)
  910. {
  911. more = w_size;
  912. }
  913. else if (more == -1)
  914. {
  915. // Very unlikely, but possible on 16 bit machine if strstart == 0
  916. // and lookahead == 1 (input done one byte at time)
  917. more--;
  918. // If the window is almost full and there is insufficient lookahead,
  919. // move the upper half to the lower one to make room in the upper half.
  920. }
  921. else if (strstart >= w_size + w_size - MIN_LOOKAHEAD)
  922. {
  923. Array.Copy(window, w_size, window, 0, w_size);
  924. match_start -= w_size;
  925. strstart -= w_size; // we now have strstart >= MAX_DIST
  926. block_start -= w_size;
  927. // Slide the hash table (could be avoided with 32 bit values
  928. // at the expense of memory usage). We slide even when level == 0
  929. // to keep the hash table consistent if we switch back to level > 0
  930. // later. (Using level 0 permanently is not an optimal usage of
  931. // zlib, so we don't care about this pathological case.)
  932. n = hash_size;
  933. p = n;
  934. do
  935. {
  936. m = (head[--p] & 0xffff);
  937. head[p] = (short)((m >= w_size) ? (m - w_size) : 0);
  938. }
  939. while (--n != 0);
  940. n = w_size;
  941. p = n;
  942. do
  943. {
  944. m = (prev[--p] & 0xffff);
  945. prev[p] = (short)((m >= w_size) ? (m - w_size) : 0);
  946. // If n is not on any hash chain, prev[n] is garbage but
  947. // its value will never be used.
  948. }
  949. while (--n != 0);
  950. more += w_size;
  951. }
  952. if (_codec.AvailableBytesIn == 0)
  953. return;
  954. // If there was no sliding:
  955. // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  956. // more == window_size - lookahead - strstart
  957. // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  958. // => more >= window_size - 2*WSIZE + 2
  959. // In the BIG_MEM or MMAP case (not yet supported),
  960. // window_size == input_size + MIN_LOOKAHEAD &&
  961. // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  962. // Otherwise, window_size == 2*WSIZE so more >= 2.
  963. // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  964. n = _codec.read_buf(window, strstart + lookahead, more);
  965. lookahead += n;
  966. // Initialize the hash value now that we have some input:
  967. if (lookahead >= MIN_MATCH)
  968. {
  969. ins_h = window[strstart] & 0xff;
  970. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  971. }
  972. // If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  973. // but this is not important since only literal bytes will be emitted.
  974. }
  975. while (lookahead < MIN_LOOKAHEAD && _codec.AvailableBytesIn != 0);
  976. }
  977. // Compress as much as possible from the input stream, return the current
  978. // block state.
  979. // This function does not perform lazy evaluation of matches and inserts
  980. // new strings in the dictionary only for unmatched strings or for short
  981. // matches. It is used only for the fast compression options.
  982. internal BlockState DeflateFast(FlushType flush)
  983. {
  984. // short hash_head = 0; // head of the hash chain
  985. int hash_head = 0; // head of the hash chain
  986. bool bflush; // set if current block must be flushed
  987. while (true)
  988. {
  989. // Make sure that we always have enough lookahead, except
  990. // at the end of the input file. We need MAX_MATCH bytes
  991. // for the next match, plus MIN_MATCH bytes to insert the
  992. // string following the next match.
  993. if (lookahead < MIN_LOOKAHEAD)
  994. {
  995. _fillWindow();
  996. if (lookahead < MIN_LOOKAHEAD && flush == FlushType.None)
  997. {
  998. return BlockState.NeedMore;
  999. }
  1000. if (lookahead == 0)
  1001. break; // flush the current block
  1002. }
  1003. // Insert the string window[strstart .. strstart+2] in the
  1004. // dictionary, and set hash_head to the head of the hash chain:
  1005. if (lookahead >= MIN_MATCH)
  1006. {
  1007. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1008. // prev[strstart&w_mask]=hash_head=head[ins_h];
  1009. hash_head = (head[ins_h] & 0xffff);
  1010. prev[strstart & w_mask] = head[ins_h];
  1011. head[ins_h] = unchecked((short)strstart);
  1012. }
  1013. // Find the longest match, discarding those <= prev_length.
  1014. // At this point we have always match_length < MIN_MATCH
  1015. if (hash_head != 0L && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD)
  1016. {
  1017. // To simplify the code, we prevent matches with the string
  1018. // of window index 0 (in particular we have to avoid a match
  1019. // of the string with itself at the start of the input file).
  1020. if (compressionStrategy != CompressionStrategy.HuffmanOnly)
  1021. {
  1022. match_length = longest_match(hash_head);
  1023. }
  1024. // longest_match() sets match_start
  1025. }
  1026. if (match_length >= MIN_MATCH)
  1027. {
  1028. // check_match(strstart, match_start, match_length);
  1029. bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
  1030. lookahead -= match_length;
  1031. // Insert new strings in the hash table only if the match length
  1032. // is not too large. This saves time but degrades compression.
  1033. if (match_length <= config.MaxLazy && lookahead >= MIN_MATCH)
  1034. {
  1035. match_length--; // string at strstart already in hash table
  1036. do
  1037. {
  1038. strstart++;
  1039. ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1040. // prev[strstart&w_mask]=hash_head=head[ins_h];
  1041. hash_head = (head[ins_h] & 0xffff);
  1042. prev[strstart & w_mask] = head[ins_h];
  1043. head[ins_h] = unchecked((short)strstart);
  1044. // strstart never exceeds WSIZE-MAX_MATCH, so there are
  1045. // always MIN_MATCH bytes ahead.
  1046. }
  1047. while (--match_length != 0);
  1048. strstart++;
  1049. }
  1050. else
  1051. {
  1052. strstart += match_length;
  1053. match_length = 0;
  1054. ins_h = window[strstart] & 0xff;
  1055. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  1056. // If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1057. // matter since it will be recomputed at next deflate call.
  1058. }
  1059. }
  1060. else
  1061. {
  1062. // No match, output a literal byte
  1063. bflush = _tr_tally(0, window[strstart] & 0xff);
  1064. lookahead--;
  1065. strstart++;
  1066. }
  1067. if (bflush)
  1068. {
  1069. flush_block_only(false);
  1070. if (_codec.AvailableBytesOut == 0)
  1071. return BlockState.NeedMore;
  1072. }
  1073. }
  1074. flush_block_only(flush == FlushType.Finish);
  1075. if (_codec.AvailableBytesOut == 0)
  1076. {
  1077. if (flush == FlushType.Finish)
  1078. return BlockState.FinishStarted;
  1079. else
  1080. return BlockState.NeedMore;
  1081. }
  1082. return flush == FlushType.Finish ? BlockState.FinishDone : BlockState.BlockDone;
  1083. }
  1084. // Same as above, but achieves better compression. We use a lazy
  1085. // evaluation for matches: a match is finally adopted only if there is
  1086. // no better match at the next window position.
  1087. internal BlockState DeflateSlow(FlushType flush)
  1088. {
  1089. // short hash_head = 0; // head of hash chain
  1090. int hash_head = 0; // head of hash chain
  1091. bool bflush; // set if current block must be flushed
  1092. // Process the input block.
  1093. while (true)
  1094. {
  1095. // Make sure that we always have enough lookahead, except
  1096. // at the end of the input file. We need MAX_MATCH bytes
  1097. // for the next match, plus MIN_MATCH bytes to insert the
  1098. // string following the next match.
  1099. if (lookahead < MIN_LOOKAHEAD)
  1100. {
  1101. _fillWindow();
  1102. if (lookahead < MIN_LOOKAHEAD && flush == FlushType.None)
  1103. return BlockState.NeedMore;
  1104. if (lookahead == 0)
  1105. break; // flush the current block
  1106. }
  1107. // Insert the string window[strstart .. strstart+2] in the
  1108. // dictionary, and set hash_head to the head of the hash chain:
  1109. if (lookahead >= MIN_MATCH)
  1110. {
  1111. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1112. // prev[strstart&w_mask]=hash_head=head[ins_h];
  1113. hash_head = (head[ins_h] & 0xffff);
  1114. prev[strstart & w_mask] = head[ins_h];
  1115. head[ins_h] = unchecked((short)strstart);
  1116. }
  1117. // Find the longest match, discarding those <= prev_length.
  1118. prev_length = match_length;
  1119. prev_match = match_start;
  1120. match_length = MIN_MATCH - 1;
  1121. if (hash_head != 0 && prev_length < config.MaxLazy &&
  1122. ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD)
  1123. {
  1124. // To simplify the code, we prevent matches with the string
  1125. // of window index 0 (in particular we have to avoid a match
  1126. // of the string with itself at the start of the input file).
  1127. if (compressionStrategy != CompressionStrategy.HuffmanOnly)
  1128. {
  1129. match_length = longest_match(hash_head);
  1130. }
  1131. // longest_match() sets match_start
  1132. if (match_length <= 5 && (compressionStrategy == CompressionStrategy.Filtered ||
  1133. (match_length == MIN_MATCH && strstart - match_start > 4096)))
  1134. {
  1135. // If prev_match is also MIN_MATCH, match_start is garbage
  1136. // but we will ignore the current match anyway.
  1137. match_length = MIN_MATCH - 1;
  1138. }
  1139. }
  1140. // If there was a match at the previous step and the current
  1141. // match is not better, output the previous match:
  1142. if (prev_length >= MIN_MATCH && match_length <= prev_length)
  1143. {
  1144. int max_insert = strstart + lookahead - MIN_MATCH;
  1145. // Do not insert strings in hash table beyond this.
  1146. // check_match(strstart-1, prev_match, prev_length);
  1147. bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
  1148. // Insert in hash table all strings up to the end of the match.
  1149. // strstart-1 and strstart are already inserted. If there is not
  1150. // enough lookahead, the last two strings are not inserted in
  1151. // the hash table.
  1152. lookahead -= (prev_length - 1);
  1153. prev_length -= 2;
  1154. do
  1155. {
  1156. if (++strstart <= max_insert)
  1157. {
  1158. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1159. //prev[strstart&w_mask]=hash_head=head[ins_h];
  1160. hash_head = (head[ins_h] & 0xffff);
  1161. prev[strstart & w_mask] = head[ins_h];
  1162. head[ins_h] = unchecked((short)strstart);
  1163. }
  1164. }
  1165. while (--prev_length != 0);
  1166. match_available = 0;
  1167. match_length = MIN_MATCH - 1;
  1168. strstart++;
  1169. if (bflush)
  1170. {
  1171. flush_block_only(false);
  1172. if (_codec.AvailableBytesOut == 0)
  1173. return BlockState.NeedMore;
  1174. }
  1175. }
  1176. else if (match_available != 0)
  1177. {
  1178. // If there was no match at the previous position, output a
  1179. // single literal. If there was a match but the current match
  1180. // is longer, truncate the previous match to a single literal.
  1181. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  1182. if (bflush)
  1183. {
  1184. flush_block_only(false);
  1185. }
  1186. strstart++;
  1187. lookahead--;
  1188. if (_codec.AvailableBytesOut == 0)
  1189. return BlockState.NeedMore;
  1190. }
  1191. else
  1192. {
  1193. // There is no previous match to compare with, wait for
  1194. // the next step to decide.
  1195. match_available = 1;
  1196. strstart++;
  1197. lookahead--;
  1198. }
  1199. }
  1200. if (match_available != 0)
  1201. {
  1202. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  1203. match_available = 0;
  1204. }
  1205. flush_block_only(flush == FlushType.Finish);
  1206. if (_codec.AvailableBytesOut == 0)
  1207. {
  1208. if (flush == FlushType.Finish)
  1209. return BlockState.FinishStarted;
  1210. else
  1211. return BlockState.NeedMore;
  1212. }
  1213. return flush == FlushType.Finish ? BlockState.FinishDone : BlockState.BlockDone;
  1214. }
  1215. internal int longest_match(int cur_match)
  1216. {
  1217. int chain_length = config.MaxChainLength; // max hash chain length
  1218. int scan = strstart; // current string
  1219. int match; // matched string
  1220. int len; // length of current match
  1221. int best_len = prev_length; // best match length so far
  1222. int limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
  1223. int niceLength = config.NiceLength;
  1224. // Stop when cur_match becomes <= limit. To simplify the code,
  1225. // we prevent matches with the string of window index 0.
  1226. int wmask = w_mask;
  1227. int strend = strstart + MAX_MATCH;
  1228. byte scan_end1 = window[scan + best_len - 1];
  1229. byte scan_end = window[scan + best_len];
  1230. // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1231. // It is easy to get rid of this optimization if necessary.
  1232. // Do not waste too much time if we already have a good match:
  1233. if (prev_length >= config.GoodLength)
  1234. {
  1235. chain_length >>= 2;
  1236. }
  1237. // Do not look for matches beyond the end of the input. This is necessary
  1238. // to make deflate deterministic.
  1239. if (niceLength > lookahead)
  1240. niceLength = lookahead;
  1241. do
  1242. {
  1243. match = cur_match;
  1244. // Skip to next match if the match length cannot increase
  1245. // or if the match length is less than 2:
  1246. if (window[match + best_len] != scan_end ||
  1247. window[match + best_len - 1] != scan_end1 ||
  1248. window[match] != window[scan] ||
  1249. window[++match] != window[scan + 1])
  1250. continue;
  1251. // The check at best_len-1 can be removed because it will be made
  1252. // again later. (This heuristic is not always a win.)
  1253. // It is not necessary to compare scan[2] and match[2] since they
  1254. // are always equal when the other bytes match, given that
  1255. // the hash keys are equal and that HASH_BITS >= 8.
  1256. scan += 2; match++;
  1257. // We check for insufficient lookahead only every 8th comparison;
  1258. // the 256th check will be made at strstart+258.
  1259. do
  1260. {
  1261. }
  1262. while (window[++scan] == window[++match] &&
  1263. window[++scan] == window[++match] &&
  1264. window[++scan] == window[++match] &&
  1265. window[++scan] == window[++match] &&
  1266. window[++scan] == window[++match] &&
  1267. window[++scan] == window[++match] &&
  1268. window[++scan] == window[++match] &&
  1269. window[++scan] == window[++match] && scan < strend);
  1270. len = MAX_MATCH - (int)(strend - scan);
  1271. scan = strend - MAX_MATCH;
  1272. if (len > best_len)
  1273. {
  1274. match_start = cur_match;
  1275. best_len = len;
  1276. if (len >= niceLength)
  1277. break;
  1278. scan_end1 = window[scan + best_len - 1];
  1279. scan_end = window[scan + best_len];
  1280. }
  1281. }
  1282. while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length != 0);
  1283. if (best_len <= lookahead)
  1284. return best_len;
  1285. return lookahead;
  1286. }
  1287. private bool Rfc1950BytesEmitted = false;
  1288. private bool _WantRfc1950HeaderBytes = true;
  1289. internal bool WantRfc1950HeaderBytes
  1290. {
  1291. get { return _WantRfc1950HeaderBytes; }
  1292. set { _WantRfc1950HeaderBytes = value; }
  1293. }
  1294. internal int Initialize(ZlibCodec codec, CompressionLevel level)
  1295. {
  1296. return Initialize(codec, level, ZlibConstants.WindowBitsMax);
  1297. }
  1298. internal int Initialize(ZlibCodec codec, CompressionLevel level, int bits)
  1299. {
  1300. return Initialize(codec, level, bits, MEM_LEVEL_DEFAULT, CompressionStrategy.Default);
  1301. }
  1302. internal int Initialize(ZlibCodec codec, CompressionLevel level, int bits, CompressionStrategy compressionStrategy)
  1303. {
  1304. return Initialize(codec, level, bits, MEM_LEVEL_DEFAULT, compressionStrategy);
  1305. }
  1306. internal int Initialize(ZlibCodec codec, CompressionLevel level, int windowBits, int memLevel, CompressionStrategy strategy)
  1307. {
  1308. _codec = codec;
  1309. _codec.Message = null;
  1310. // validation
  1311. if (windowBits < 9 || windowBits > 15)
  1312. throw new ZlibException("windowBits must be in the range 9..15.");
  1313. if (memLevel < 1 || memLevel > MEM_LEVEL_MAX)
  1314. throw new ZlibException(String.Format("memLevel must be in the range 1.. {0}", MEM_LEVEL_MAX));
  1315. _codec.dstate = this;
  1316. w_bits = windowBits;
  1317. w_size = 1 << w_bits;
  1318. w_mask = w_size - 1;
  1319. hash_bits = memLevel + 7;
  1320. hash_size = 1 << hash_bits;
  1321. hash_mask = hash_size - 1;
  1322. hash_shift = ((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  1323. window = new byte[w_size * 2];
  1324. prev = new short[w_size];
  1325. head = new short[hash_size];
  1326. // for memLevel==8, this will be 16384, 16k
  1327. lit_bufsize = 1 << (memLevel + 6);
  1328. // Use a single array as the buffer for data pending compression,
  1329. // the output distance codes, and the output length codes (aka tree).
  1330. // orig comment: This works just fine since the average
  1331. // output size for (length,distance) codes is <= 24 bits.
  1332. pending = new byte[lit_bufsize * 4];
  1333. _distanceOffset = lit_bufsize;
  1334. _lengthOffset = (1 + 2) * lit_bufsize;
  1335. // So, for memLevel 8, the length of the pending buffer is 65536. 64k.
  1336. // The first 16k are pending bytes.
  1337. // The middle slice, of 32k, is used for distance codes.
  1338. // The final 16k are length codes.
  1339. this.compressionLevel = level;
  1340. this.compressionStrategy = strategy;
  1341. Reset();
  1342. return ZlibConstants.Z_OK;
  1343. }
  1344. internal void Reset()
  1345. {
  1346. _codec.TotalBytesIn = _codec.TotalBytesOut = 0;
  1347. _codec.Message = null;
  1348. //strm.data_type = Z_UNKNOWN;
  1349. pendingCount = 0;
  1350. nextPending = 0;
  1351. Rfc1950BytesEmitted = false;
  1352. status = (WantRfc1950HeaderBytes) ? INIT_STATE : BUSY_STATE;
  1353. _codec._Adler32 = Adler.Adler32(0, null, 0, 0);
  1354. last_flush = (int)FlushType.None;
  1355. _InitializeTreeData();
  1356. _InitializeLazyMatch();
  1357. }
  1358. internal int End()
  1359. {
  1360. if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE)
  1361. {
  1362. return ZlibConstants.Z_STREAM_ERROR;
  1363. }
  1364. // Deallocate in reverse order of allocations:
  1365. pending = null;
  1366. head = null;
  1367. prev = null;
  1368. window = null;
  1369. // free
  1370. // dstate=null;
  1371. return status == BUSY_STATE ? ZlibConstants.Z_DATA_ERROR : ZlibConstants.Z_OK;
  1372. }
  1373. private void SetDeflater()
  1374. {
  1375. switch (config.Flavor)
  1376. {
  1377. case DeflateFlavor.Store:
  1378. DeflateFunction = DeflateNone;
  1379. break;
  1380. case DeflateFlavor.Fast:
  1381. DeflateFunction = DeflateFast;
  1382. break;
  1383. case DeflateFlavor.Slow:
  1384. DeflateFunction = DeflateSlow;
  1385. break;
  1386. }
  1387. }
  1388. internal int SetParams(CompressionLevel level, CompressionStrategy strategy)
  1389. {
  1390. int result = ZlibConstants.Z_OK;
  1391. if (compressionLevel != level)
  1392. {
  1393. Config newConfig = Config.Lookup(level);
  1394. // change in the deflate flavor (Fast vs slow vs none)?
  1395. if (newConfig.Flavor != config.Flavor && _codec.TotalBytesIn != 0)
  1396. {
  1397. // Flush the last buffer:
  1398. result = _codec.Deflate(FlushType.Partial);
  1399. }
  1400. compressionLevel = level;
  1401. config = newConfig;
  1402. SetDeflater();
  1403. }
  1404. // no need to flush with change in strategy? Really?
  1405. compressionStrategy = strategy;
  1406. return result;
  1407. }
  1408. internal int SetDictionary(byte[] dictionary)
  1409. {
  1410. int length = dictionary.Length;
  1411. int index = 0;
  1412. if (dictionary == null || status != INIT_STATE)
  1413. throw new ZlibException("Stream error.");
  1414. _codec._Adler32 = Adler.Adler32(_codec._Adler32, dictionary, 0, dictionary.Length);
  1415. if (length < MIN_MATCH)
  1416. return ZlibConstants.Z_OK;
  1417. if (length > w_size - MIN_LOOKAHEAD)
  1418. {
  1419. length = w_size - MIN_LOOKAHEAD;
  1420. index = dictionary.Length - length; // use the tail of the dictionary
  1421. }
  1422. Array.Copy(dictionary, index, window, 0, length);
  1423. strstart = length;
  1424. block_start = length;
  1425. // Insert all strings in the hash table (except for the last two bytes).
  1426. // s->lookahead stays null, so s->ins_h will be recomputed at the next
  1427. // call of fill_window.
  1428. ins_h = window[0] & 0xff;
  1429. ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
  1430. for (int n = 0; n <= length - MIN_MATCH; n++)
  1431. {
  1432. ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1433. prev[n & w_mask] = head[ins_h];
  1434. head[ins_h] = (short)n;
  1435. }
  1436. return ZlibConstants.Z_OK;
  1437. }
  1438. internal int Deflate(FlushType flush)
  1439. {
  1440. int old_flush;
  1441. if (_codec.OutputBuffer == null ||
  1442. (_codec.InputBuffer == null && _codec.AvailableBytesIn != 0) ||
  1443. (status == FINISH_STATE && flush != FlushType.Finish))
  1444. {
  1445. _codec.Message = _ErrorMessage[ZlibConstants.Z_NEED_DICT - (ZlibConstants.Z_STREAM_ERROR)];
  1446. throw new ZlibException(String.Format("Something is fishy. [{0}]", _codec.Message));
  1447. }
  1448. if (_codec.AvailableBytesOut == 0)
  1449. {
  1450. _codec.Message = _ErrorMessage[ZlibConstants.Z_NEED_DICT - (ZlibConstants.Z_BUF_ERROR)];
  1451. throw new ZlibException("OutputBuffer is full (AvailableBytesOut == 0)");
  1452. }
  1453. old_flush = last_flush;
  1454. last_flush = (int)flush;
  1455. // Write the zlib (rfc1950) header bytes
  1456. if (status == INIT_STATE)
  1457. {
  1458. int header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
  1459. int level_flags = (((int)compressionLevel - 1) & 0xff) >> 1;
  1460. if (level_flags > 3)
  1461. level_flags = 3;
  1462. header |= (level_flags << 6);
  1463. if (strstart != 0)
  1464. header |= PRESET_DICT;
  1465. header += 31 - (header % 31);
  1466. status = BUSY_STATE;
  1467. //putShortMSB(header);
  1468. unchecked
  1469. {
  1470. pending[pendingCount++] = (byte)(header >> 8);
  1471. pending[pendingCount++] = (byte)header;
  1472. }
  1473. // Save the adler32 of the preset dictionary:
  1474. if (strstart != 0)
  1475. {
  1476. pending[pendingCount++] = (byte)((_codec._Adler32 & 0xFF000000) >> 24);
  1477. pending[pendingCount++] = (byte)((_codec._Adler32 & 0x00FF0000) >> 16);
  1478. pending[pendingCount++] = (byte)((_codec._Adler32 & 0x0000FF00) >> 8);
  1479. pending[pendingCount++] = (byte)(_codec._Adler32 & 0x000000FF);
  1480. }
  1481. _codec._Adler32 = Adler.Adler32(0, null, 0, 0);
  1482. }
  1483. // Flush as much pending output as possible
  1484. if (pendingCount != 0)
  1485. {
  1486. _codec.flush_pending();
  1487. if (_codec.AvailableBytesOut == 0)
  1488. {
  1489. //System.out.println(" avail_out==0");
  1490. // Since avail_out is 0, deflate will be called again with
  1491. // more output space, but possibly with both pending and
  1492. // avail_in equal to zero. There won't be anything to do,
  1493. // but this is not an error situation so make sure we
  1494. // return OK instead of BUF_ERROR at next call of deflate:
  1495. last_flush = -1;
  1496. return ZlibConstants.Z_OK;
  1497. }
  1498. // Make sure there is something to do and avoid duplicate consecutive
  1499. // flushes. For repeated and useless calls with Z_FINISH, we keep
  1500. // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  1501. }
  1502. else if (_codec.AvailableBytesIn == 0 &&
  1503. (int)flush <= old_flush &&
  1504. flush != FlushType.Finish)
  1505. {
  1506. // workitem 8557
  1507. //
  1508. // Not sure why this needs to be an error. pendingCount == 0, which
  1509. // means there's nothing to deflate. And the caller has not asked
  1510. // for a FlushType.Finish, but... that seems very non-fatal. We
  1511. // can just say "OK" and do nothing.
  1512. // _codec.Message = z_errmsg[ZlibConstants.Z_NEED_DICT - (ZlibConstants.Z_BUF_ERROR)];
  1513. // throw new ZlibException("AvailableBytesIn == 0 && flush<=old_flush && flush != FlushType.Finish");
  1514. return ZlibConstants.Z_OK;
  1515. }
  1516. // User must not provide more input after the first FINISH:
  1517. if (status == FINISH_STATE && _codec.AvailableBytesIn != 0)
  1518. {
  1519. _codec.Message = _ErrorMessage[ZlibConstants.Z_NEED_DICT - (ZlibConstants.Z_BUF_ERROR)];
  1520. throw new ZlibException("status == FINISH_STATE && _codec.AvailableBytesIn != 0");
  1521. }
  1522. // Start a new block or continue the current one.
  1523. if (_codec.AvailableBytesIn != 0 || lookahead != 0 || (flush != FlushType.None && status != FINISH_STATE))
  1524. {
  1525. BlockState bstate = DeflateFunction(flush);
  1526. if (bstate == BlockState.FinishStarted || bstate == BlockState.FinishDone)
  1527. {
  1528. status = FINISH_STATE;
  1529. }
  1530. if (bstate == BlockState.NeedMore || bstate == BlockState.FinishStarted)
  1531. {
  1532. if (_codec.AvailableBytesOut == 0)
  1533. {
  1534. last_flush = -1; // avoid BUF_ERROR next call, see above
  1535. }
  1536. return ZlibConstants.Z_OK;
  1537. // If flush != Z_NO_FLUSH && avail_out == 0, the next call
  1538. // of deflate should use the same flush parameter to make sure
  1539. // that the flush is complete. So we don't have to output an
  1540. // empty block here, this will be done at next call. This also
  1541. // ensures that for a very small output buffer, we emit at most
  1542. // one empty block.
  1543. }
  1544. if (bstate == BlockState.BlockDone)
  1545. {
  1546. if (flush == FlushType.Partial)
  1547. {
  1548. _tr_align();
  1549. }
  1550. else
  1551. {
  1552. // FlushType.Full or FlushType.Sync
  1553. _tr_stored_block(0, 0, false);
  1554. // For a full flush, this empty block will be recognized
  1555. // as a special marker by inflate_sync().
  1556. if (flush == FlushType.Full)
  1557. {
  1558. // clear hash (forget the history)
  1559. for (int i = 0; i < hash_size; i++)
  1560. head[i] = 0;
  1561. }
  1562. }
  1563. _codec.flush_pending();
  1564. if (_codec.AvailableBytesOut == 0)
  1565. {
  1566. last_flush = -1; // avoid BUF_ERROR at next call, see above
  1567. return ZlibConstants.Z_OK;
  1568. }
  1569. }
  1570. }
  1571. if (flush != FlushType.Finish)
  1572. return ZlibConstants.Z_OK;
  1573. if (!WantRfc1950HeaderBytes || Rfc1950BytesEmitted)
  1574. return ZlibConstants.Z_STREAM_END;
  1575. // Write the zlib trailer (adler32)
  1576. pending[pendingCount++] = (byte)((_codec._Adler32 & 0xFF000000) >> 24);
  1577. pending[pendingCount++] = (byte)((_codec._Adler32 & 0x00FF0000) >> 16);
  1578. pending[pendingCount++] = (byte)((_codec._Adler32 & 0x0000FF00) >> 8);
  1579. pending[pendingCount++] = (byte)(_codec._Adler32 & 0x000000FF);
  1580. //putShortMSB((int)(SharedUtils.URShift(_codec._Adler32, 16)));
  1581. //putShortMSB((int)(_codec._Adler32 & 0xffff));
  1582. _codec.flush_pending();
  1583. // If avail_out is zero, the application will call deflate again
  1584. // to flush the rest.
  1585. Rfc1950BytesEmitted = true; // write the trailer only once!
  1586. return pendingCount != 0 ? ZlibConstants.Z_OK : ZlibConstants.Z_STREAM_END;
  1587. }
  1588. }
  1589. }