Deflate.cs 74 KB

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