ZlibCodec.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. // ZlibCodec.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-November-03 15:40:51>
  19. //
  20. // ------------------------------------------------------------------
  21. //
  22. // This module defines a Codec for ZLIB compression and
  23. // decompression. This code extends code that was based the jzlib
  24. // implementation of zlib, but this code is completely novel. The codec
  25. // class is new, and encapsulates some behaviors that are new, and some
  26. // that were present in other classes in the jzlib code base. In
  27. // keeping with the license for jzlib, the copyright to the jzlib code
  28. // is included below.
  29. //
  30. // ------------------------------------------------------------------
  31. //
  32. // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
  33. //
  34. // Redistribution and use in source and binary forms, with or without
  35. // modification, are permitted provided that the following conditions are met:
  36. //
  37. // 1. Redistributions of source code must retain the above copyright notice,
  38. // this list of conditions and the following disclaimer.
  39. //
  40. // 2. Redistributions in binary form must reproduce the above copyright
  41. // notice, this list of conditions and the following disclaimer in
  42. // the documentation and/or other materials provided with the distribution.
  43. //
  44. // 3. The names of the authors may not be used to endorse or promote products
  45. // derived from this software without specific prior written permission.
  46. //
  47. // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  48. // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  49. // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  50. // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  51. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  52. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  53. // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  54. // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  55. // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  56. // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  57. //
  58. // -----------------------------------------------------------------------
  59. //
  60. // This program is based on zlib-1.1.3; credit to authors
  61. // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  62. // and contributors of zlib.
  63. //
  64. // -----------------------------------------------------------------------
  65. using System;
  66. namespace SharpCompress.Compressors.Deflate
  67. {
  68. /// <summary>
  69. /// Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951).
  70. /// </summary>
  71. ///
  72. /// <remarks>
  73. /// This class compresses and decompresses data according to the Deflate algorithm
  74. /// and optionally, the ZLIB format, as documented in <see
  75. /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950 - ZLIB</see> and <see
  76. /// href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951 - DEFLATE</see>.
  77. /// </remarks>
  78. internal sealed class ZlibCodec
  79. {
  80. /// <summary>
  81. /// The buffer from which data is taken.
  82. /// </summary>
  83. public byte[] InputBuffer;
  84. /// <summary>
  85. /// An index into the InputBuffer array, indicating where to start reading.
  86. /// </summary>
  87. public int NextIn;
  88. /// <summary>
  89. /// The number of bytes available in the InputBuffer, starting at NextIn.
  90. /// </summary>
  91. /// <remarks>
  92. /// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call.
  93. /// The class will update this number as calls to Inflate/Deflate are made.
  94. /// </remarks>
  95. public int AvailableBytesIn;
  96. /// <summary>
  97. /// Total number of bytes read so far, through all calls to Inflate()/Deflate().
  98. /// </summary>
  99. public long TotalBytesIn;
  100. /// <summary>
  101. /// Buffer to store output data.
  102. /// </summary>
  103. public byte[] OutputBuffer;
  104. /// <summary>
  105. /// An index into the OutputBuffer array, indicating where to start writing.
  106. /// </summary>
  107. public int NextOut;
  108. /// <summary>
  109. /// The number of bytes available in the OutputBuffer, starting at NextOut.
  110. /// </summary>
  111. /// <remarks>
  112. /// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call.
  113. /// The class will update this number as calls to Inflate/Deflate are made.
  114. /// </remarks>
  115. public int AvailableBytesOut;
  116. /// <summary>
  117. /// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate().
  118. /// </summary>
  119. public long TotalBytesOut;
  120. /// <summary>
  121. /// used for diagnostics, when something goes wrong!
  122. /// </summary>
  123. public String Message;
  124. internal DeflateManager dstate;
  125. internal InflateManager istate;
  126. internal uint _Adler32;
  127. /// <summary>
  128. /// The compression level to use in this codec. Useful only in compression mode.
  129. /// </summary>
  130. public CompressionLevel CompressLevel = CompressionLevel.Default;
  131. /// <summary>
  132. /// The number of Window Bits to use.
  133. /// </summary>
  134. /// <remarks>
  135. /// This gauges the size of the sliding window, and hence the
  136. /// compression effectiveness as well as memory consumption. It's best to just leave this
  137. /// setting alone if you don't know what it is. The maximum value is 15 bits, which implies
  138. /// a 32k window.
  139. /// </remarks>
  140. public int WindowBits = ZlibConstants.WindowBitsDefault;
  141. /// <summary>
  142. /// The compression strategy to use.
  143. /// </summary>
  144. /// <remarks>
  145. /// This is only effective in compression. The theory offered by ZLIB is that different
  146. /// strategies could potentially produce significant differences in compression behavior
  147. /// for different data sets. Unfortunately I don't have any good recommendations for how
  148. /// to set it differently. When I tested changing the strategy I got minimally different
  149. /// compression performance. It's best to leave this property alone if you don't have a
  150. /// good feel for it. Or, you may want to produce a test harness that runs through the
  151. /// different strategy options and evaluates them on different file types. If you do that,
  152. /// let me know your results.
  153. /// </remarks>
  154. public CompressionStrategy Strategy = CompressionStrategy.Default;
  155. /// <summary>
  156. /// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this.
  157. /// </summary>
  158. public int Adler32 => (int)_Adler32;
  159. /// <summary>
  160. /// Create a ZlibCodec.
  161. /// </summary>
  162. /// <remarks>
  163. /// If you use this default constructor, you will later have to explicitly call
  164. /// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress
  165. /// or decompress.
  166. /// </remarks>
  167. public ZlibCodec()
  168. {
  169. }
  170. /// <summary>
  171. /// Create a ZlibCodec that either compresses or decompresses.
  172. /// </summary>
  173. /// <param name="mode">
  174. /// Indicates whether the codec should compress (deflate) or decompress (inflate).
  175. /// </param>
  176. public ZlibCodec(CompressionMode mode)
  177. {
  178. if (mode == CompressionMode.Compress)
  179. {
  180. int rc = InitializeDeflate();
  181. if (rc != ZlibConstants.Z_OK)
  182. {
  183. throw new ZlibException("Cannot initialize for deflate.");
  184. }
  185. }
  186. else if (mode == CompressionMode.Decompress)
  187. {
  188. int rc = InitializeInflate();
  189. if (rc != ZlibConstants.Z_OK)
  190. {
  191. throw new ZlibException("Cannot initialize for inflate.");
  192. }
  193. }
  194. else
  195. {
  196. throw new ZlibException("Invalid ZlibStreamFlavor.");
  197. }
  198. }
  199. /// <summary>
  200. /// Initialize the inflation state.
  201. /// </summary>
  202. /// <remarks>
  203. /// It is not necessary to call this before using the ZlibCodec to inflate data;
  204. /// It is implicitly called when you call the constructor.
  205. /// </remarks>
  206. /// <returns>Z_OK if everything goes well.</returns>
  207. public int InitializeInflate()
  208. {
  209. return InitializeInflate(WindowBits);
  210. }
  211. /// <summary>
  212. /// Initialize the inflation state with an explicit flag to
  213. /// govern the handling of RFC1950 header bytes.
  214. /// </summary>
  215. ///
  216. /// <remarks>
  217. /// By default, the ZLIB header defined in <see
  218. /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If
  219. /// you want to read a zlib stream you should specify true for
  220. /// expectRfc1950Header. If you have a deflate stream, you will want to specify
  221. /// false. It is only necessary to invoke this initializer explicitly if you
  222. /// want to specify false.
  223. /// </remarks>
  224. ///
  225. /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte
  226. /// pair when reading the stream of data to be inflated.</param>
  227. ///
  228. /// <returns>Z_OK if everything goes well.</returns>
  229. public int InitializeInflate(bool expectRfc1950Header)
  230. {
  231. return InitializeInflate(WindowBits, expectRfc1950Header);
  232. }
  233. /// <summary>
  234. /// Initialize the ZlibCodec for inflation, with the specified number of window bits.
  235. /// </summary>
  236. /// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
  237. /// then you shouldn't be calling this initializer.</param>
  238. /// <returns>Z_OK if all goes well.</returns>
  239. public int InitializeInflate(int windowBits)
  240. {
  241. WindowBits = windowBits;
  242. return InitializeInflate(windowBits, true);
  243. }
  244. /// <summary>
  245. /// Initialize the inflation state with an explicit flag to govern the handling of
  246. /// RFC1950 header bytes.
  247. /// </summary>
  248. ///
  249. /// <remarks>
  250. /// If you want to read a zlib stream you should specify true for
  251. /// expectRfc1950Header. In this case, the library will expect to find a ZLIB
  252. /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
  253. /// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or
  254. /// GZIP stream, which does not have such a header, you will want to specify
  255. /// false.
  256. /// </remarks>
  257. ///
  258. /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading
  259. /// the stream of data to be inflated.</param>
  260. /// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
  261. /// then you shouldn't be calling this initializer.</param>
  262. /// <returns>Z_OK if everything goes well.</returns>
  263. public int InitializeInflate(int windowBits, bool expectRfc1950Header)
  264. {
  265. WindowBits = windowBits;
  266. if (dstate != null)
  267. {
  268. throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate().");
  269. }
  270. istate = new InflateManager(expectRfc1950Header);
  271. return istate.Initialize(this, windowBits);
  272. }
  273. /// <summary>
  274. /// Inflate the data in the InputBuffer, placing the result in the OutputBuffer.
  275. /// </summary>
  276. /// <remarks>
  277. /// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and
  278. /// AvailableBytesOut before calling this method.
  279. /// </remarks>
  280. /// <example>
  281. /// <code>
  282. /// private void InflateBuffer()
  283. /// {
  284. /// int bufferSize = 1024;
  285. /// byte[] buffer = new byte[bufferSize];
  286. /// ZlibCodec decompressor = new ZlibCodec();
  287. ///
  288. /// Console.WriteLine("\n============================================");
  289. /// Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length);
  290. /// MemoryStream ms = new MemoryStream(DecompressedBytes);
  291. ///
  292. /// int rc = decompressor.InitializeInflate();
  293. ///
  294. /// decompressor.InputBuffer = CompressedBytes;
  295. /// decompressor.NextIn = 0;
  296. /// decompressor.AvailableBytesIn = CompressedBytes.Length;
  297. ///
  298. /// decompressor.OutputBuffer = buffer;
  299. ///
  300. /// // pass 1: inflate
  301. /// do
  302. /// {
  303. /// decompressor.NextOut = 0;
  304. /// decompressor.AvailableBytesOut = buffer.Length;
  305. /// rc = decompressor.Inflate(FlushType.None);
  306. ///
  307. /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END)
  308. /// throw new Exception("inflating: " + decompressor.Message);
  309. ///
  310. /// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
  311. /// }
  312. /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0);
  313. ///
  314. /// // pass 2: finish and flush
  315. /// do
  316. /// {
  317. /// decompressor.NextOut = 0;
  318. /// decompressor.AvailableBytesOut = buffer.Length;
  319. /// rc = decompressor.Inflate(FlushType.Finish);
  320. ///
  321. /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK)
  322. /// throw new Exception("inflating: " + decompressor.Message);
  323. ///
  324. /// if (buffer.Length - decompressor.AvailableBytesOut &gt; 0)
  325. /// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut);
  326. /// }
  327. /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0);
  328. ///
  329. /// decompressor.EndInflate();
  330. /// }
  331. ///
  332. /// </code>
  333. /// </example>
  334. /// <param name="flush">The flush to use when inflating.</param>
  335. /// <returns>Z_OK if everything goes well.</returns>
  336. public int Inflate(FlushType flush)
  337. {
  338. if (istate == null)
  339. {
  340. throw new ZlibException("No Inflate State!");
  341. }
  342. return istate.Inflate(flush);
  343. }
  344. /// <summary>
  345. /// Ends an inflation session.
  346. /// </summary>
  347. /// <remarks>
  348. /// Call this after successively calling Inflate(). This will cause all buffers to be flushed.
  349. /// After calling this you cannot call Inflate() without a intervening call to one of the
  350. /// InitializeInflate() overloads.
  351. /// </remarks>
  352. /// <returns>Z_OK if everything goes well.</returns>
  353. public int EndInflate()
  354. {
  355. if (istate == null)
  356. {
  357. throw new ZlibException("No Inflate State!");
  358. }
  359. int ret = istate.End();
  360. istate = null;
  361. return ret;
  362. }
  363. /// <summary>
  364. /// I don't know what this does!
  365. /// </summary>
  366. /// <returns>Z_OK if everything goes well.</returns>
  367. public int SyncInflate()
  368. {
  369. if (istate == null)
  370. {
  371. throw new ZlibException("No Inflate State!");
  372. }
  373. return istate.Sync();
  374. }
  375. /// <summary>
  376. /// Initialize the ZlibCodec for deflation operation.
  377. /// </summary>
  378. /// <remarks>
  379. /// The codec will use the MAX window bits and the default level of compression.
  380. /// </remarks>
  381. /// <example>
  382. /// <code>
  383. /// int bufferSize = 40000;
  384. /// byte[] CompressedBytes = new byte[bufferSize];
  385. /// byte[] DecompressedBytes = new byte[bufferSize];
  386. ///
  387. /// ZlibCodec compressor = new ZlibCodec();
  388. ///
  389. /// compressor.InitializeDeflate(CompressionLevel.Default);
  390. ///
  391. /// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
  392. /// compressor.NextIn = 0;
  393. /// compressor.AvailableBytesIn = compressor.InputBuffer.Length;
  394. ///
  395. /// compressor.OutputBuffer = CompressedBytes;
  396. /// compressor.NextOut = 0;
  397. /// compressor.AvailableBytesOut = CompressedBytes.Length;
  398. ///
  399. /// while (compressor.TotalBytesIn != TextToCompress.Length &amp;&amp; compressor.TotalBytesOut &lt; bufferSize)
  400. /// {
  401. /// compressor.Deflate(FlushType.None);
  402. /// }
  403. ///
  404. /// while (true)
  405. /// {
  406. /// int rc= compressor.Deflate(FlushType.Finish);
  407. /// if (rc == ZlibConstants.Z_STREAM_END) break;
  408. /// }
  409. ///
  410. /// compressor.EndDeflate();
  411. ///
  412. /// </code>
  413. /// </example>
  414. /// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns>
  415. public int InitializeDeflate()
  416. {
  417. return _InternalInitializeDeflate(true);
  418. }
  419. /// <summary>
  420. /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel.
  421. /// </summary>
  422. /// <remarks>
  423. /// The codec will use the maximum window bits (15) and the specified
  424. /// CompressionLevel. It will emit a ZLIB stream as it compresses.
  425. /// </remarks>
  426. /// <param name="level">The compression level for the codec.</param>
  427. /// <returns>Z_OK if all goes well.</returns>
  428. public int InitializeDeflate(CompressionLevel level)
  429. {
  430. CompressLevel = level;
  431. return _InternalInitializeDeflate(true);
  432. }
  433. /// <summary>
  434. /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
  435. /// and the explicit flag governing whether to emit an RFC1950 header byte pair.
  436. /// </summary>
  437. /// <remarks>
  438. /// The codec will use the maximum window bits (15) and the specified CompressionLevel.
  439. /// If you want to generate a zlib stream, you should specify true for
  440. /// wantRfc1950Header. In this case, the library will emit a ZLIB
  441. /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
  442. /// 1950</see>, in the compressed stream.
  443. /// </remarks>
  444. /// <param name="level">The compression level for the codec.</param>
  445. /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
  446. /// <returns>Z_OK if all goes well.</returns>
  447. public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header)
  448. {
  449. CompressLevel = level;
  450. return _InternalInitializeDeflate(wantRfc1950Header);
  451. }
  452. /// <summary>
  453. /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
  454. /// and the specified number of window bits.
  455. /// </summary>
  456. /// <remarks>
  457. /// The codec will use the specified number of window bits and the specified CompressionLevel.
  458. /// </remarks>
  459. /// <param name="level">The compression level for the codec.</param>
  460. /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
  461. /// <returns>Z_OK if all goes well.</returns>
  462. public int InitializeDeflate(CompressionLevel level, int bits)
  463. {
  464. CompressLevel = level;
  465. WindowBits = bits;
  466. return _InternalInitializeDeflate(true);
  467. }
  468. /// <summary>
  469. /// Initialize the ZlibCodec for deflation operation, using the specified
  470. /// CompressionLevel, the specified number of window bits, and the explicit flag
  471. /// governing whether to emit an RFC1950 header byte pair.
  472. /// </summary>
  473. ///
  474. /// <param name="level">The compression level for the codec.</param>
  475. /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
  476. /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
  477. /// <returns>Z_OK if all goes well.</returns>
  478. public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header)
  479. {
  480. CompressLevel = level;
  481. WindowBits = bits;
  482. return _InternalInitializeDeflate(wantRfc1950Header);
  483. }
  484. private int _InternalInitializeDeflate(bool wantRfc1950Header)
  485. {
  486. if (istate != null)
  487. {
  488. throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate().");
  489. }
  490. dstate = new DeflateManager();
  491. dstate.WantRfc1950HeaderBytes = wantRfc1950Header;
  492. return dstate.Initialize(this, CompressLevel, WindowBits, Strategy);
  493. }
  494. /// <summary>
  495. /// Deflate one batch of data.
  496. /// </summary>
  497. /// <remarks>
  498. /// You must have set InputBuffer and OutputBuffer before calling this method.
  499. /// </remarks>
  500. /// <example>
  501. /// <code>
  502. /// private void DeflateBuffer(CompressionLevel level)
  503. /// {
  504. /// int bufferSize = 1024;
  505. /// byte[] buffer = new byte[bufferSize];
  506. /// ZlibCodec compressor = new ZlibCodec();
  507. ///
  508. /// Console.WriteLine("\n============================================");
  509. /// Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length);
  510. /// MemoryStream ms = new MemoryStream();
  511. ///
  512. /// int rc = compressor.InitializeDeflate(level);
  513. ///
  514. /// compressor.InputBuffer = UncompressedBytes;
  515. /// compressor.NextIn = 0;
  516. /// compressor.AvailableBytesIn = UncompressedBytes.Length;
  517. ///
  518. /// compressor.OutputBuffer = buffer;
  519. ///
  520. /// // pass 1: deflate
  521. /// do
  522. /// {
  523. /// compressor.NextOut = 0;
  524. /// compressor.AvailableBytesOut = buffer.Length;
  525. /// rc = compressor.Deflate(FlushType.None);
  526. ///
  527. /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END)
  528. /// throw new Exception("deflating: " + compressor.Message);
  529. ///
  530. /// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut);
  531. /// }
  532. /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0);
  533. ///
  534. /// // pass 2: finish and flush
  535. /// do
  536. /// {
  537. /// compressor.NextOut = 0;
  538. /// compressor.AvailableBytesOut = buffer.Length;
  539. /// rc = compressor.Deflate(FlushType.Finish);
  540. ///
  541. /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK)
  542. /// throw new Exception("deflating: " + compressor.Message);
  543. ///
  544. /// if (buffer.Length - compressor.AvailableBytesOut &gt; 0)
  545. /// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
  546. /// }
  547. /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0);
  548. ///
  549. /// compressor.EndDeflate();
  550. ///
  551. /// ms.Seek(0, SeekOrigin.Begin);
  552. /// CompressedBytes = new byte[compressor.TotalBytesOut];
  553. /// ms.Read(CompressedBytes, 0, CompressedBytes.Length);
  554. /// }
  555. /// </code>
  556. /// </example>
  557. /// <param name="flush">whether to flush all data as you deflate. Generally you will want to
  558. /// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to
  559. /// flush everything.
  560. /// </param>
  561. /// <returns>Z_OK if all goes well.</returns>
  562. public int Deflate(FlushType flush)
  563. {
  564. if (dstate == null)
  565. {
  566. throw new ZlibException("No Deflate State!");
  567. }
  568. return dstate.Deflate(flush);
  569. }
  570. /// <summary>
  571. /// End a deflation session.
  572. /// </summary>
  573. /// <remarks>
  574. /// Call this after making a series of one or more calls to Deflate(). All buffers are flushed.
  575. /// </remarks>
  576. /// <returns>Z_OK if all goes well.</returns>
  577. public int EndDeflate()
  578. {
  579. if (dstate == null)
  580. {
  581. throw new ZlibException("No Deflate State!");
  582. }
  583. // TODO: dinoch Tue, 03 Nov 2009 15:39 (test this)
  584. //int ret = dstate.End();
  585. dstate = null;
  586. return ZlibConstants.Z_OK; //ret;
  587. }
  588. /// <summary>
  589. /// Reset a codec for another deflation session.
  590. /// </summary>
  591. /// <remarks>
  592. /// Call this to reset the deflation state. For example if a thread is deflating
  593. /// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first
  594. /// block and before the next Deflate(None) of the second block.
  595. /// </remarks>
  596. /// <returns>Z_OK if all goes well.</returns>
  597. public void ResetDeflate()
  598. {
  599. if (dstate == null)
  600. {
  601. throw new ZlibException("No Deflate State!");
  602. }
  603. dstate.Reset();
  604. }
  605. /// <summary>
  606. /// Set the CompressionStrategy and CompressionLevel for a deflation session.
  607. /// </summary>
  608. /// <param name="level">the level of compression to use.</param>
  609. /// <param name="strategy">the strategy to use for compression.</param>
  610. /// <returns>Z_OK if all goes well.</returns>
  611. public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy)
  612. {
  613. if (dstate == null)
  614. {
  615. throw new ZlibException("No Deflate State!");
  616. }
  617. return dstate.SetParams(level, strategy);
  618. }
  619. /// <summary>
  620. /// Set the dictionary to be used for either Inflation or Deflation.
  621. /// </summary>
  622. /// <param name="dictionary">The dictionary bytes to use.</param>
  623. /// <returns>Z_OK if all goes well.</returns>
  624. public int SetDictionary(byte[] dictionary)
  625. {
  626. if (istate != null)
  627. {
  628. return istate.SetDictionary(dictionary);
  629. }
  630. if (dstate != null)
  631. {
  632. return dstate.SetDictionary(dictionary);
  633. }
  634. throw new ZlibException("No Inflate or Deflate state!");
  635. }
  636. // Flush as much pending output as possible. All deflate() output goes
  637. // through this function so some applications may wish to modify it
  638. // to avoid allocating a large strm->next_out buffer and copying into it.
  639. // (See also read_buf()).
  640. internal void flush_pending()
  641. {
  642. int len = dstate.pendingCount;
  643. if (len > AvailableBytesOut)
  644. {
  645. len = AvailableBytesOut;
  646. }
  647. if (len == 0)
  648. {
  649. return;
  650. }
  651. if (dstate.pending.Length <= dstate.nextPending ||
  652. OutputBuffer.Length <= NextOut ||
  653. dstate.pending.Length < (dstate.nextPending + len) ||
  654. OutputBuffer.Length < (NextOut + len))
  655. {
  656. throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})",
  657. dstate.pending.Length, dstate.pendingCount));
  658. }
  659. Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len);
  660. NextOut += len;
  661. dstate.nextPending += len;
  662. TotalBytesOut += len;
  663. AvailableBytesOut -= len;
  664. dstate.pendingCount -= len;
  665. if (dstate.pendingCount == 0)
  666. {
  667. dstate.nextPending = 0;
  668. }
  669. }
  670. // Read a new buffer from the current input stream, update the adler32
  671. // and total number of bytes read. All deflate() input goes through
  672. // this function so some applications may wish to modify it to avoid
  673. // allocating a large strm->next_in buffer and copying from it.
  674. // (See also flush_pending()).
  675. internal int read_buf(byte[] buf, int start, int size)
  676. {
  677. int len = AvailableBytesIn;
  678. if (len > size)
  679. {
  680. len = size;
  681. }
  682. if (len == 0)
  683. {
  684. return 0;
  685. }
  686. AvailableBytesIn -= len;
  687. if (dstate.WantRfc1950HeaderBytes)
  688. {
  689. _Adler32 = Adler.Adler32(_Adler32, InputBuffer, NextIn, len);
  690. }
  691. Array.Copy(InputBuffer, NextIn, buf, start, len);
  692. NextIn += len;
  693. TotalBytesIn += len;
  694. return len;
  695. }
  696. }
  697. }