Deflate.cs 74 KB

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