DeflateManager.cs 76 KB

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